我尝试了一个java挑战,其中我猜一个随机数,程序会告诉我它是否正确。
然而,程序在while循环处停止并告诉我只能在程序运行时输入:
public class javaChallenge1
{
// Instance variables
int number = 0;
int guess = 0;
boolean gameFinished = false;
// Core variables
Scanner keyboard = new Scanner(System.in);
Random rand = new Random();
public void sampleMethod()
{
number = rand.nextInt(100);
System.out.println("Guess the number generated.");
while (gameFinished = false)
{
guess = keyboard.nextInt();
keyboard.nextLine();
if (guess == number) {
System.out.println("Congrats! You have guessed the number correctly.");
gameFinished = true;
} else {
System.out.println("Bad luck. Try again.");
}
keyboard.nextLine();
}
}
}
答案 0 :(得分:4)
错误在这一行:
while(gameFinished = false)
您不要检查该值是否为false,而是将值false赋值给您的变量。
您应该将==
代替=
写入比较值,而不是分配
while(gameFinished == false)
答案 1 :(得分:0)
如果您想要比较 gameFinished
与false
,请使用==
运算符:
while (gameFinished == false)
以下将gameFinished
的值更改为false
,然后检查它是否为true
。所以循环停止了。
while (gameFinished = false)
答案 2 :(得分:-1)
在while循环中你应该放置条件,但是你赋予了值。所以请更换
gameFinished = false
至
gameFinished == false