我遇到了这段代码的问题。 我看到的问题是,当用户运行代码并且正确猜测或使用最大尝试次数时,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;
}
答案 0 :(得分:1)
Single&#34; =&#34;是一个赋值运算符,只需将其更改为double&#34; ==&#34;。
while(repeat == true)
答案 1 :(得分:1)
除了ugur所说的,你可以简单地做到
while(repeat)
因为repeat是一个布尔变量(返回true或false)
答案 2 :(得分:0)
检查您正在设置repeat=false
的外部循环中的最后一行。因此,当您从内部循环break
时,外部while
检查重复,除了第一个之外每次都是假。