【发布时间】:2013-05-24 20:28:03
【问题描述】:
我有这段代码,我想捕捉字母异常,但它一直出现这些错误:
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中。 -
是的,似乎是这种情况,但我怎样才能同时检查两者(字母和负数异常)?
-
简单。只需删除您发布的前 2 行代码即可。
-
如果我删除前两行,那么我会在 while 循环中得到一个错误,因为学生不会有值
-
不,你不会。
students是int,它们总是有一个值(默认为 0)。
标签: java exception-handling while-loop try-catch mismatch