javaexceptionwhile-looptry-catchinputmismatchexception

Try-Catch inside While Loop


The code below asks the user how many racers he/she would like.

while (true) { // loops forever until break
    try { // checks code for exceptions
        System.out.println("How many racers should" + " participate in the race?");
        amountRacers = in.nextInt();
        break; // if no exceptions breaks out of loop
    } 
    catch (InputMismatchException e) { // if an exception appears prints message below
        System.err.println("Please enter a number! " + e.getMessage());
        continue; // continues to loop if exception is found
    }
}

If a number is entered at amoutnRacers = in.nextInt(); the code breaks out of the loop and the rest of the program runs fine; however, when I enter something such as "awredsf" it should catch that exception, which it does. Instead of prompting the user again it loops continuously, which to me does not make sense.

The program prints like this when looping continuously:

How many racers should participate in the race? How many racers should participate in the race? How many racers should participate in the race? How many racers should participate in the race? How many racers should participate in the race? How many racers should participate in the race? How many racers should participate in the race?Please enter a number! null Please enter a number! null Please enter a number! null Please enter a number! null Please enter a number! null Please enter a number! null Please enter a number! null ...

I do not understand what is going on amountRacers = in.nextInt(); so why is the user not able to enter a number?


Solution

  • Just add input.next() once you catch InputMismatchException.

    catch (InputMismatchException e) { //if an exception appears prints message below
        System.err.println("Please enter a number! " + e.getMessage());
        input.next(); // clear scanner wrong input
        continue; // continues to loop if exception is found
    }
    

    You need to clear the wrong input, which scanner automatically does not.