我正在制作一个模拟器,看看随机数生成器用来“滚动”蛇眼的次数。该程序只是重复
Not snake eyes yet :(
以下是代码:
import java.util.Random;
public class SnakeEyes {
public static void main(String[] args) {
Random myRandom = new Random();
int die1 = 0, tries = 0, die2 = 0;
System.out.println("Welcome to SEO (Snake Eyes Operator)!");
System.out.println("How many rolls will it take you to get to snake eyes! ");
die1 = myRandom.nextInt(6) + 1;
die2 = myRandom.nextInt(6) + 1;
while (die1 + die2 != 2) {
System.out.println("Not snake eyes yet :( ");
tries = +1;
}
System.out.print("You have rolled snake eyes! ");
System.out.print("Congratulations! It only took you ");
System.out.print(tries);
System.out.print("!");
}
}
我认为这是一个开环的问题,但我不确定。谢谢!
答案 0 :(得分:5)
使用while循环时,必须更新检查的值或循环永不停止。
您需要更新循环内的die1
和die2
值。
答案 1 :(得分:2)
一旦这个while (die1 + die2 != 2)
条件失败,它将进入无限循环,必须有一个条件来打破循环。
试试这个(在10次迭代后会破坏循环):
while (die1 + die2 != 2) {
System.out.println("Not snake eyes yet :( ");
die1 = myRandom.nextInt(6) + 1;
die2 = myRandom.nextInt(6) + 1;
tries += 1;
if(tries==10)
break;
}
并将tries = +1;
替换为tries += 1;
答案 2 :(得分:0)
您需要在myRandom.nextInt(6) + 1;
循环中指定<{1}} 1>},否则将通过反复检查相同的值进行迭代。
答案 3 :(得分:0)
die1 + die2
没有改变,因此如果满足以下条件,循环将永远运行:
while (die1 + die2 != 2)
因此,您可能需要在while循环中添加逻辑以逻辑更新die1
和/或die2
的值。