我只是制作一个简单的猜谜游戏。如果用户输入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()循环中的条件可能不正确。我稍微改变了它之前的状态,这是一段时间(猜测!= secretNumber); 。也许这样做会更好,我们应该以不同的方式对待0? 感谢。
答案 0 :(得分:3)
问题是你增加了除第一个之外的所有猜测:
System.out.println("Your number: \n");
guess = scan.nextInt();
guess++;
因此他们需要输入-1
来猜测0并结束循环。他们还需要输入少于secretNumber
的一个来进行正确的猜测....
答案 1 :(得分:1)
为什么你需要在最后一行猜猜++?
删除猜测++或将其注释掉,你应该没问题
答案 2 :(得分:0)
首先提出guess == 0
条件。由于0小于任何生成的数字,因此它将首先进入该条件。
答案 3 :(得分:0)
如果这是他们输入的第一个数字,它会正常退出,但除此之外它只会增加,如猜测数量的总和
这一行导致了这一点,据我所知,你的代码不需要:
guess++;
答案 4 :(得分:0)
这是你应该做的: -
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
{
// Exit condition is being checked first so that control does not enter
// the less-than-secret-number-condition which would always be true for zero
if(guess==0)
break;
// If its not zero, num of guesses is to be incremented
numGuess++;
if(guess==secretNumber)
{
System.out.println("You guessed the number!");
break; // Exits if it is zero or the secret number
}
else if(guess<secretNumber)
{
System.out.println("Your guess is too low! Guess again");
// Commenting out the increment as its already done
// numGuess++;
}
else if(guess>secretNumber)
{
System.out.println("Your guess is too high! Guess again");
// Commenting out the increment as its already done
// numGuess++;
}
System.out.println("Your number: \n");
guess = scan.nextInt();
// guess++ has been removed as I think it serves no purpose. numGuess is the variable maintaining the count
}
while(true); // Changed the condition here as the exit conditions have already bee dealt with within the loop