[英]Problem with while loop in guessing game?
我面臨着讓游戲結束的問題!
如果用戶的 numberOfTries >4,我創建 int numberOfTries = 0 並嘗試結束游戲。 我想不通問題出在哪里?
do {
int theNumber = (int) (Math.random() * 100 +1 );
int guess = 0;
int numberOfTries = 0;
while (guess != theNumber){
System.out.println("Guess a number between 1 and 100");
guess = scan.nextInt();
if (guess< theNumber) {
System.out.println(guess + " is too low.");
numberOfTries += 1 ;
}
else if ( guess > theNumber) {
System.out.println(guess + " is too high.");
numberOfTries += 1;
}
else if(guess == theNumber) {
System.out.println(guess + " is correct!");
if (numberOfTries == 1 ){
System.out.println("You are a genius!");
}
else if (numberOfTries == 0){
System.out.println("You are a pure genius!");
}
else if (numberOfTries <=4 ){
System.out.println("It only took you " + numberOfTries +
" Good Job!");
}
}
else if (numberOfTries > 4){
System.out.println("Game over!");
}
}
System.out.println("Would you like to play again?(y/n)");
playAgain = scan.next();
}while (playAgain.equalsIgnoreCase("y"));
System.out.println("Thank you for playing this game! Good Bye!");
scan.close();
}
}
誰能給我解釋一下,好嗎? 謝謝
當您的嘗試次數超過 4 時,您應該打破循環。不僅僅是打印出消息。
您的 if 語句總是進入三個條件之一,因此永遠不會進入最后一個條件。 一種解決方案是改變這個:
else if (numberOfTries > 4){
System.out.println("Game over!");
}
為了這:
if (numberOfTries > 4){
System.out.println("Game over!");
break;
}
您的 if else 構造如下所示:
if (guess< theNumber) {
}
else if ( guess > theNumber) {
}
else if(guess == theNumber) {
}
else if (numberOfTries > 4){
}
所以首先你問猜測是否小於數字,然后如果不是這樣,如果它更大,然后如果不是這樣,如果它相等。
現在,您的 if-else 構造已經用盡了所有可能的狀態,因為一個數字必須大於、小於或等於另一個數字,因此您的最后一個 else if 永遠不會被輸入。
只需將最后一個 else if 更改為正常 if:
if (numberOfTries > 4){
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.