循环播放直到您随机滚动选定的数字,然后在哪里随机

时间:2019-05-07 11:38:42

标签: java loops random while-loop

在练习while循环时,我尝试制作代码,在其中放置随机数,然后猜测要滚动多少次才能尝试,但是我无法在while内声明变量“机会”,但是如果我将其置于变量之前,则保持滚动1个数字。

NotePad++

我如何声明int机会,使其进入while循环?

3 个答案:

答案 0 :(得分:2)

您可以在while循环中将机会重新分配给新值:

int count = 0;
int chance = rng.nextInt((100)+1);
while (choice != chance) {
    System.out.println(chance);
    chance = rng.nextInt((100)+1);
    count++;
}

答案 1 :(得分:2)

如果我理解您的问题,我认为您应该使用do-while循环。它将一次进入循环至少

Random rng = new Random();
Scanner input = new Scanner(System.in);
System.out.println("Select a number you want to roll");
int choice = input.nextInt();
System.out.println("You feelin' lucky?\nHow many tries until you get " + choice);
int tries = input.nextInt();
int count = 0;

do {
   int chance = rng.nextInt((100)+1);
   System.out.println(chance);
   count++;
} while (choice != chance)

System.out.println("You won! It only took " + count + " tries.");

答案 2 :(得分:1)

不再声明变量chance。只需将其重新分配为新值即可。

chance = rng.nextInt((100)+1);

发出代码:

  1. 循环从不使用tries
  2. 代码无法确定何时尝试次数不足以猜测 用户输入的数字

以下内容针对他们:

Random rng = new Random();
Scanner input = new Scanner(System.in);
System.out.println("Select a number you want to roll");
int choice = input.nextInt();
System.out.println("You feelin' lucky?\nHow many tries until you get " + choice);
int tries = input.nextInt();
int count = 1;
int chance = rng.nextInt((100) + 1);

while (tries > 0) {
    System.out.println(chance);
    if (choice == chance)
        break;
    chance = rng.nextInt((100) + 1);
    count++;
    tries--;
}

if (choice == chance) {
    System.out.println("You won! It only took " + count + " tries.");
} else {
    System.out.println("You lost");
}

逻辑:

  1. 使用tries来确定运行循环需要多少次。 每次运行后将其减小。
  2. 如果选择和机会相等,则控制跳转
  3. 最后一个if条件是确定用户是否能够 猜出尝试次数