我该如何使用InputMismatchException来确定输入到Scanner中的值不是整数?基本上,如果他们输入单词而不是整数,我需要使用InputMismatchException返回一条消息。
while (true) {
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
try{
Integer.parseInt(i);
} catch (InputMismatchException e) {
System.out.println("Sorry, " + i + " is not a number.");
}
if (i == 1) {
System.out.println("1 was selected");
} else {
System.out.println("1 was not selected");
}
sc.nextInt();
这一行抛出,而不是通过执行Integer.parseInt(i);
来抛出。因此,将int i = sc.nextInt();
放在try catch中处理该异常,就可以解决问题了。 - 3kings