我目前正在学习try-catch代码块,并且正在编写一段代码,该代码从用户处获取输入并检查其是否为整数。我的代码是
int classSize = 0;
boolean error = false;
do {
try{
System.out.println("Hello! Please enter how many Students you have in your class: ");
classSize = in.nextInt();
error = false;
}
catch(InputMismatchException e){
System.out.println("Invalid input. please make sure you enter numbers ONLY! No symbols or letters.");
classSize = in.nextInt();
error = true;
}
}while(error);
当我尝试通过输入字母进行测试时,我同时收到错误消息和try阻止消息。
Hello! Please enter how many Students you have in your class:
asdfsda
Invalid input. please make sure you enter numbers ONLY! No symbols or
letters.
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at ExcerciseOne.main(ExcerciseOne.java:65)
为什么显示catch块和错误消息?我是否正确使用try-catch块?
答案 0 :(得分:3)
您正在捕获$school->ratings->status
子句中引发的异常,但是随后您再次从try
内部的扫描程序中读取并因此引发了另一个未捕获的异常。
catch
在两个子句中都存在,两次都抛出异常,但是只有从classSize = in.nextInt();
子句内部抛出时才会被捕获。
答案 1 :(得分:1)
在in.nextInt()
块中进行的catch
调用读取在in.nextInt()
块中对try
的第一次调用留下的不良流。
您可以做的是删除.nextInt()
块中的catch
个调用:
boolean hasError = true;
while (hasError) {
try {
System.out.println("Hello! Please enter how many Students you have in your class: ");
classSize = in.nextInt();
hasError = false;
} catch (InputMismatchException e) {
System.out.println("Invalid input. please make sure you enter numbers ONLY! No symbols or letters.");
// variable has error remains true
}
}
或更佳:
由于InputMismatchException
是RuntimeException
的子类,因此可以通过if
语句过滤掉引发此错误的错误类型。由于只需要一个适当的整数作为输入,因此可以使用正则表达式来验证输入。
boolean hasError = true;
String integerRegex = "[\\d]+"; // it means 1-to-many digits
while (hasError) {
System.out.println("Hello! Please enter how many Students you have in your class: ");
String input = in.nextLine();
if (input.matches(integerRegex)) {
classSize = Integer.parseInt(input);
hasError = false;
} else {
System.out.println("Invalid input. please make sure you enter numbers ONLY! No symbols or letters.");
// variable hasError remains true
}
}
答案 2 :(得分:1)
Gendarme的答案很明确,我为您添加了一个正确的演示:
public static void main(String[] args) {
int studentsCount = 0;
boolean hasError;
do {
try {
System.out.println("Hello! Please enter how many Students you have in your class: ");
Scanner in = new Scanner(System.in);
studentsCount = in.nextInt();
hasError = false;
} catch (InputMismatchException e) {
System.out.println("--> Invalid input. please make sure you enter numbers ONLY! No symbols or letters.");
hasError = true;
}
} while (hasError);
System.out.println("There are " + studentsCount + " students in your class.");
}