这是给我的作业。但我似乎无法理解我的程序有什么问题,以及如何解决它。它只是不停地滚动骰子并冻结我的JCreator。我甚至尝试将NUMBER值更改为10,它仍然会做同样的事情。
答案 0 :(得分:1)
我认为你理解的做法是错误的。
只要while括号内的表达式为真,就会执行“do {...}”部分(掷骰子的地方)。
将整个“if(die1Value == die2Value)”部分(直到“counter ++;”行)移动到do大括号中,它应该运行。
答案 1 :(得分:1)
do
{
die1Value = generator.nextInt(6) + 1;
System.out.println("You rolled: " + die1Value);
die2Value = generator.nextInt(6) + 1;
System.out.println("You rolled: " + die2Value);
}
while (count <= NUMBER);
第一个关键字执行会使而永久循环整个块,因为计数变量仅在下一个块上递增。 我的建议是删除执行:
//do
//{
die1Value = generator.nextInt(6) + 1;
System.out.println("You rolled: " + die1Value);
die2Value = generator.nextInt(6) + 1;
System.out.println("You rolled: " + die2Value);
//}
while (count <= NUMBER)
{
...
}
因为你已经有一段时间了。
答案 2 :(得分:1)
您没有正确使用doop循环。你有一个do循环和while循环,而不是一个do循环。在do循环中,计数永远不会增加,因此循环永远不会结束。 do循环在评估是否继续之前执行第一次迭代。
import java.util.Random;
public class DiceSimulation
{
public static void main(String[] args)
{
final int NUMBER = 10000;
Random generator = new Random();
int die1Value;
int die2Value;
int count = 0;
int snakeEyes = 0;
int twos = 0;
int threes = 0;
int fours = 0;
int fives = 0;
int sixes = 0;
do{
die1Value = generator.nextInt(6) + 1;
System.out.println("You rolled: " + die1Value);
die2Value = generator.nextInt(6) + 1;
System.out.println("You rolled: " + die2Value);
if (die1Value == die2Value)
{
if(die1Value == 1)
{
snakeEyes++;
}
else if (die1Value == 2)
{
twos++;
}
else if (die1Value == 3)
{
threes++;
}
else if (die1Value == 4)
{
fours++;
}
else if (die1Value == 5)
{
fives++;
}
else if (die1Value == 6)
{
sixes++;
}
}
count++;
}while (count < NUMBER);
System.out.println ("You rolled snake eyes " + snakeEyes +
" out of " + count + " rolls.");
System.out.println ("You rolled double twos " + twos +
" out of " + count + " rolls.");
System.out.println ("You rolled double threes " + threes +
" out of " + count + " rolls.");
System.out.println ("You rolled double fours " + fours +
" out of " + count + " rolls.");
System.out.println ("You rolled double fives " + fives +
" out of " + count + " rolls.");
System.out.println ("You rolled double sixes " + sixes +
" out of " + count + " rolls.");
}
}