0

我正在制作一个模拟器来查看随机数生成器需要多少次来“滚动”蛇眼。程序只是重复

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("!");

}

}

我相信这是开环的问题,但我不确定。谢谢!

4

4 回答 4

5

当您使用 while 循环时,您必须更新您检查的值,否则循环将永远不会停止。

您需要在循环内更新die1和值。die2

于 2013-09-12T05:32:48.347 回答
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;

于 2013-09-12T05:33:43.347 回答
0

您需要在循环myRandom.nextInt(6) + 1; 内部while进行分配,否则它将通过一遍又一遍地检查相同的值来进行迭代。

于 2013-09-12T05:33:38.617 回答
0
die1 + die2 

没有改变,因此如果满足以下条件,循环将永远运行:

while (die1 + die2 != 2)

因此,您可能必须在您的 while 循环中添加一个逻辑,以在逻辑上更新die1和/或的值die2

于 2013-09-12T05:34:03.620 回答