我有這樣的代碼,我想趕上字母例外,但它一直有這些錯誤:的Java InputMismatchException時
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)
這裏是我的代碼:
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();'不在'try'塊中,而你輸入的東西不能存儲在'int'中。 – jlordo
是的,似乎是這種情況,但我怎樣才能同時檢查(字母和負數除外)? –
簡單。只需刪除您發佈的前兩行代碼即可。 – jlordo