我正在嘗試開發一個簡單的高低遊戲,如果玩家想要再玩一次後會詢問用戶。如果我刪除外部while循環,內部循環的邏輯完全按照我希望的方式執行,但是我不確定如何用外部循環來包裝內部循環,這將再次詢問播放問題,如果答案是肯定的他們回到內部循環。以下是我的代碼。似乎無法重複我的低高的遊戲
import java.util.Scanner;
import java.util.Random;
public class HiLoGuess {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in); // Creates scanner object.
Random numb = new Random(); // Creates an instance of the random class.
int guess = -1; // Placeholder for users guess.
int answer = numb.nextInt(100)+1; // Generates a random number for the game.
int count = 0; // Placeholder for the guess counter.
int sentinel = 0; // Placeholder for players answer as to whether they want to play again or not.
String newgame = "y";
while (newgame.equalsIgnoreCase("y"))
{
while (guess != sentinel && guess != answer) //Loop that ends when user enters a zero.
{
System.out.println ("Enter a number between 1-100 or 0 to quit");
guess = scan.nextInt();
count++;
if (guess < answer && guess > 0)
{
System.out.println("Your guess is too low, guess again");
}
else if (guess > answer)
{
System.out.println ("Your guess is to high, guess again");
}
else if (guess == answer)
{
System.out.println();
System.out.println ("You guessed correctly, you win!!!");
System.out.println ("It took you " + count + " guesses");
}
}
System.out.print();
System.out.println("Play another game: y or n?");
newgame = scan.nextLine();
}
}
}
我不認爲這是解決方案。小心解釋爲什麼? –
nextLine只返回被跳過的行,而下一個給你下一個標記 –
你能編輯你的答案來解釋爲什麼發生這種情況嗎? –