Java InputMismatchException

You can use a do-while loop instead to eliminate the first input.nextInt().

int students = 0;
do {
    try {
        // Get input 
        System.out.print("Enter the number of students: ");
        students = input.nextInt();
    } catch (InputMismatchException e) {
        System.out.print("Invalid number of students. ");
    }
    input.nextLine(); // clears the buffer
} while (students <= 0);

// Do something with guaranteed valid value 

Therefore all InputMismatchException can be handled in one place.

Leave a Comment