Java InputMismatchException

I have this code and I want to catch the exception of the letter, but it saves these errors:

Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:840) at java.util.Scanner.next(Scanner.java:1461) at java.util.Scanner.nextInt(Scanner.java:2091) at java.util.Scanner.nextInt(Scanner.java:2050) at exercise_one.Exercise.main(Exercise.java:17) 

And here is my code:

  System.out.print("Enter the number of students: "); students = input.nextInt(); while (students <= 0) { try { System.out.print("Enter the number of students: "); students = input.nextInt(); } catch (InputMismatchException e) { System.out.print("Enter the number of students"); } } 
+4
source share
2 answers

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(); // clears the buffer } while (students <= 0); 

Therefore, all InputMismatchException can be handled in one place.

+7
source

from doc

Scanner.nextInt Scans the next input token as int. if the next token does not match the Integer regular expression or does not match the Range

So it seems you are not entering an 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(); } } 
+2
source

Source: https://habr.com/ru/post/1483370/


All Articles