【发布时间】:2017-04-05 01:48:40
【问题描述】:
我正在尝试学习 try-catch 的用法,并且必须验证输入,以便用户必须输入 1 或 2 才能继续程序。我相信我已经接近了,但如果用户输入错误的内容,例如“3”或“2.12”,似乎无法让程序继续运行。
这是我所拥有的:
String input = " ";
try {
Scanner scan = new Scanner(System.in);
input = scan.next();
Integer.parseInt(input);
if (!input.equals("1") && !input.equals("2")) {
System.out.println();
System.out.println("Invalid imput! Please select '1' or '2':");
}
} catch (InputMismatchException a) {
System.out.println();
System.out.println("Invalid imput! Please select '1' or '2':");
}
【问题讨论】:
-
if (!input.equals("1") && !input.equals("2")) { throw new InputMismatchException (); -
当来自扫描仪的输入不同于预期的类型(不是值)时,您会抛出 InputMismatchException。为你的 scnerio 抛出 InputMismatchException 是在滥用它。