Instead, you can use the do-while loop to exclude 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();
Therefore, all InputMismatchException can be handled in one place.
source share