虽然循环返回不正确的回应

问题描述:

我试图做出一个高低数猜测游戏,报告给用户,如果他们的猜测太高,太低或准确。除了成功的猜测(所有的事情)之外,一切都按预期工作。输入正确的数字后,循环会输出“您的猜测是正确的”声明以及尝试次数。这是我想要的。但是,与其询问用户是否希望下一次重播,它正在返回“太高”的响应。我是否错误地嵌套了?虽然循环返回不正确的回应

import java.util.Scanner; 
import java.util.Random; 
public class hilo2 { 



    public static void main(String[] args) { 

    int guess = 0; 
    int attempts; 
    String quit; 
    boolean replay = true; 

    Scanner scan = new Scanner(System.in); 

    Random generator = new Random(); 


    while (replay) { 
      attempts = 0; 
      int answer = generator.nextInt(101) + 1; 
      System.out.println(answer);//for testing 
      System.out.println("Guess a number between 1 and 100. Enter your  guess (0 to quit): "); 
      guess = scan.nextInt(); 
      scan.nextLine(); 

      while (guess != 0){ 


      if (guess < answer) { 
       System.out.println("You guess was too low. Guess again (0 to quit): "); 
       guess = scan.nextInt(); 
       scan.nextLine(); 
       attempts++; 
      } 
      else if (guess > answer) { 
       System.out.println("Your guess was too high. Guess again (0 to quit): "); 
       guess = scan.nextInt(); 
       scan.nextLine(); 
       attempts++; 
      } 

      else { 
       System.out.println("Your guess was correct!"); 
       attempts++; 
       System.out.println("Number of guesses: " + attempts); 
       answer = 0; 
      } 

     } 
     System.out.println("Would you like to play again? (y/n): "); 
     String input = scan.nextLine(); 
     if (input.equalsIgnoreCase("n")) { 
      replay = false; 
     } 
    } 
} 

} 
+0

'else'中的'scan.nextLine()' – theblindprophet

当你有

while (guess != 0){ 

改变你的代码来跳出循环

else { 
      System.out.println("Your guess was correct!"); 
      attempts++; 
      System.out.println("Number of guesses: " + attempts); 
      answer = 0; 
      break; // add this or change above line to guess = 0; 
} 

while (guess != 0) { 
    if (guess < answer) { 
     System.out.println("You guess was too low. Guess again (0 to quit): "); 
     guess = scan.nextInt(); 
     scan.nextLine(); 
     attempts++; 
    } else if (guess > answer) { 
     System.out.println("Your guess was too high. Guess again (0 to quit): "); 
     guess = scan.nextInt(); 
     scan.nextLine(); 
     attempts++; 
    } else { 
     System.out.println("Your guess was correct!"); 
     attempts++; 
     System.out.println("Number of guesses: " + attempts); 
     answer = 0; 
    } 
} 

你还没有嵌套的错,但是你没有条件这会中止while循环。

您将设置answer为0,然后再回到while循环&年初发现的猜测是现在过高,因为答案是0

我想你想做的事guess = 0;。或者你也可以在那里放一个break;