我只是在做一个简单的猜谜游戏。如果用户输入 0,我需要我的 do-while 循环退出。按照它的方式,如果这是他们输入的第一个数字,它会正确退出,否则它只会随着猜测数的总和而增加。这是我的代码:
System.out.println("The system will generate a random number between 1 and 100."
+ " Your goal is to guess this number.");
do
{
Random secretNumberGen = new Random();
int secretNumber = secretNumberGen.nextInt(100)+1;
System.out.println("Enter a number between 1 and 100: ");
guess = scan.nextInt();
do
{
if(guess==secretNumber)
{
System.out.println("You guessed the number!");
}
else if(guess<secretNumber)
{
System.out.println("Your guess is too low! Guess again");
numGuess++;
}
else if(guess>secretNumber)
{
System.out.println("Your guess is too high! Guess again");
numGuess++;
}
else if(guess==0)
break;
System.out.println("Your number: \n");
guess = scan.nextInt();
guess++;
}
while(guess!=0&&guess!=secretNumber);
我猜我的 while() 循环中的条件可能不正确。我从以前的方式稍微改变了它,它是 while(guess!=secretNumber); . 也许最好保持原样,我们应该以不同的方式对待输入 0?谢谢。