我對此代碼有問題。 我看到的問題是,當用戶運行代碼並猜測正確或使用最大嘗試次數時,while循環不會啓動並允許遊戲重新啓動。 我的想法是將計數器(嘗試)重置爲零並重新開始,但我只是以總分來獲得退出消息。如何在數字猜測遊戲循環時重新啓動
int guess = 0;
int attempt = 0;
int number = new Random().nextInt(1000) + 1;
int scorePlayer = 0; int scoreComputer = 0;
boolean repeat;
System.out.println("Hello and welcome to the number guessing game.");
System.out.println("Please guess a number between 1 and 1000");
while(repeat == true){
do{
Scanner scan = new Scanner(System.in);
guess = Integer.parseInt(scan.nextLine());
System.out.println("The number you guessed is "+guess);
attempt++;
if(guess == number){
System.out.println("Congratulations! You got it!!");
scorePlayer++;
System.out.println("Would you like to play again? [YES/NO]");
Scanner a = new Scanner(System.in);
String answer = a.nextLine().toUpperCase();
if (answer != "YES"){
//repeat = false;
System.out.println("Thank you for playing");
System.out.println("The final score is "+scorePlayer+" to you and "+scoreComputer+" to the server");
if (scorePlayer<scoreComputer){
System.out.println("Computer wins!");
}else{
System.out.println("You win!");
}break;
}else{
attempt = 0;
}
}else if(guess < number){
System.out.println("That is incorrect, try a larger number");
}else if(guess > number){
System.out.println("That is incorrect, try a smaller number");
}if(attempt == 10 && guess != number){
System.out.println("That is the max number of guesses allowed");
System.out.println("The number you were looking for is "+number);
scoreComputer++;
System.out.println("Would you like to play again? [YES/NO]");
Scanner b = new Scanner(System.in);
String answer = b.nextLine().toUpperCase();
if (answer != "YES"){
//repeat = false;
System.out.println("Thank you for playing");
System.out.println("The final score is "+scorePlayer+" to you and "+scoreComputer+" to the server");
if (scorePlayer<scoreComputer){
System.out.println("Computer wins!");
}else{
System.out.println("You win!");
}break;
}else{
attempt = 0;
}
}
}while(guess != number || attempt == 0);
repeat = false;
}
假設你修正了編譯器錯誤'while(repeat = true)':你在第一個內部'do-while'循環完成之後直接''repeat'設置爲'false'。那麼外環的想法是什麼呢?它只運行一次。 – AKSW