I have this code and I want to catch the letter exception but it keeps having 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");
}
}
students = input.nextInt();
is not inside thetry
block and your entering something that can't be stored in a anint
. – Philipsstudents
is anint
, and they always have a value (default is 0). – Philipsint
orInteger
? Where you declare it, you can also assign 0 to it... – Philipsinput.nextLine();
to thecatch
block. – Philips