【发布时间】:2019-07-15 08:07:17
【问题描述】:
尝试编写一个掷骰子 3 次的程序,一旦你连续获得 3 个 6,它就会打印出尝试了多少次。代码末尾有问题,|| 之间的差异和&&,好像是相反的,看看……
package javaapplication12;
import java.util.*;
public class JavaApplication12 {
public static void main(String[] args) {
Random rand = new Random();
// this should try to cast a die 3 times and keep doing that until we get 3 6s in a row and counter
// how many tries it takes to get that.
int array[] = new int[3]; // creating 3 places for castin our die 3 times in a row
int counter1 = 0; // creating a counter to track each time we try to cast 3 die ( 3 cast = 1 try)
do{
counter1++;
System.out.println("try " + counter1); // prints out counter in the beginning of every try.
for (int counter = 0; counter < array.length; counter++ ){
array[counter]=(rand.nextInt(6)+1); // a loop that fills the array with random numbers from 1-6
}
for(int x: array)
{System.out.println(x);} // this is for our own to check if we have 3 6s in a row,
// prints out all the numbers in out array
}
//so this is the I'veusing part, i've written 3 scenarios that can be written for the condtion in our
// do- while loop...
while (array[0]+array[1]+array[2] != 18); // this works just fine.
while (array[0] !=6 || array[1] != 6 || array[2] != 6); // imo this should not work but surprisingly it does
while (array[0] !=6 && array[1] != 6 && array[2] != 6); // this should work, but it doesnt.
}
}
【问题讨论】:
-
一做,就可以一会。所以你唯一的while条件应该是
while (array[0] !=6 && array[1] != 6 && array[2] != 6); -
我知道我暂时只写了 3 个场景,是的,一个应该可以工作,但它没有。奇怪的是,如果我最后一次使用 &&,它会在骰子值达到 6 时结束循环,而不是全部。以及带有 || 的第二个 while 选项工作得很好,当我们连续获得 3 个 6 时停止循环,这就是为什么这很奇怪......它应该是相反的。
-
您使用的“die”标签与掷骰子无关,而是与使用名为 die() 的函数有关(顺便说一句,该函数在 java 中不存在)。请删除它。