Java InputMismatchException

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

do {
    try {
        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);

Therefore all InputMismatchException can be handled in one place.


from the doc

Scanner.nextInt Scans the next token of the input as an int. if the next token does not match the Integer regular expression, or is out of range

So it seems you are not entering any integer as input.

you can use

     while (students <= 0) {

         try {
            System.out.print("Enter the number of students: ");

            students = input1.nextInt();

         }

         catch (InputMismatchException e) {
             input1.nextLine();
         }
     }