[英]How to exit a do-while loop using a Scanner in Java when the user enters the word “exit”?
[英]Can't figure out how to handle quitting do-while loop when user enters 0
我只是在做一個簡單的猜謎游戲。 如果用戶輸入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()循環中的條件可能不正確。 我從以前的那段時間(guess!= secretNumber)稍作更改。 。 也許現在更好,我們應該以其他方式輸入0? 謝謝。
問題是您增加了除第一個猜測以外的所有猜測:
System.out.println("Your number: \n");
guess = scan.nextInt();
guess++;
因此,他們需要輸入-1
才能猜測為0並結束循環。 他們還需要輸入比secretNumber
小一的secretNumber
以進行正確的猜測。
為什么您需要在最后第二行使用guess ++?
刪除猜測++或將其注釋掉,您應該會沒事的
首先將您的guess == 0
條件。 由於0小於任何生成的數字,它將首先進入該條件。
如果這是他們輸入的第一個數字,它會正確退出,否則它將作為猜測總數的總和而增加
此行導致這一點,據我了解,不需要您的代碼:
guess++;
這是您應該做的:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.