【发布时间】:2019-09-25 01:36:44
【问题描述】:
在练习 while 循环时,我尝试在您放置随机数的位置编写代码,然后您猜测滚动它需要多少次尝试,但我不能在 while 内声明变量“机会”,但如果我把它放在它之前它只是保持滚动 1 个数字。
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;
int chance = rng.nextInt((100)+1);
while (choice != chance) {
System.out.println(chance);
count++;
}
System.out.println("You won! It only took " + count + " tries.");
}
如何声明 int 机会使其进入 while 循环?
【问题讨论】:
-
您需要在循环内重新分配机会...即
chance = rng.nextInt(101); -
你知道它可能永远运行吗?
标签: java loops random while-loop