在练习while循环时,我尝试制作代码,在其中放置随机数,然后猜测要滚动多少次才能尝试,但是我无法在while内声明变量“机会”,但是如果我将其置于变量之前,则保持滚动1个数字。
NotePad++
我如何声明int机会,使其进入while循环?
答案 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);
发出代码:
tries
。以下内容针对他们:
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");
}
逻辑:
tries
来确定运行循环需要多少次。
每次运行后将其减小。