Try catch block causing infinite loop? [duplicate]

2019-03-04 06:13发布

问题:

This question already has an answer here:

  • try/catch with InputMismatchException creates infinite loop 7 answers

I am writing a simple java console game. I use the scanner to read the input from the console. I am trying to verify that it I ask for an integer, I don't get an error if a letter is entered. I tried this:

boolean validResponce = false;
int choice = 0;
while (!validResponce)
{
    try
    {
        choice = stdin.nextInt();
        validResponce = true;
    }
    catch (java.util.InputMismatchException ex)
    {
        System.out.println("I did not understand what you said. Try again: ");
    }
}

but it seems to create an infinite loop, just printing out the catch block. What am I doing wrong.

And yes, I am new to Java

回答1:

nextInt() won't discard the mismatched output; the program will try to read it over and over again, failing each time. Use the hasNextInt() method to determine whether there's an int available to be read before calling nextInt().

Make sure that when you find something in the InputStream other than an integer you clear it with nextLine() because hasNextInt() also doesn't discard input, it just tests the next token in the input stream.



回答2:

Try using

boolean isInValidResponse = true;
//then
while(isInValidResponse){
//makes more sense and is less confusing
    try{
        //let user know you are now asking for a number, don't just leave empty console
        System.out.println("Please enter a number: ");
        String lineEntered = stdin.nextLine(); //as suggested in accepted answer, it will allow you to exit console waiting for more integers from user
        //test if user entered a number in that line
        int number=Integer.parseInt(lineEntered);
        System.out.println("You entered a number: "+number);
        isInValidResponse = false;
    }
//it tries to read integer from input, the exceptions should be either NumberFormatException, IOException or just Exception
    catch (Exception e){
        System.out.println("I did not understand what you said. Try again: ");
    }
}

Because of common topic of avoiding negative conditionals https://blog.jetbrains.com/idea/2014/09/the-inspection-connection-issue-2/