[英]How to restart while loop in Number Guessing Game
我對此代碼有疑問。 我所看到的問題是,當用戶運行代碼並正確猜測或使用最大嘗試次數時,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)
除了ugur所說的,您還可以做
while(repeat)
因為repeat是一個布爾變量(返回true或false)
檢查您設置了repeat=false
的外循環中的最后一行。 因此,當您從內部循環break
時, while
檢查重復的while
外部循環,每次除第一次外都為假。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.