我只想获得int
age
值
但是当用户输入字符串时,为什么我不能再获得一个int?
这是我的代码:
public static void getAge() throws InputMismatchException {
System.out.print("Enter Your age: ");
try {
age = in.nextInt();
} catch (InputMismatchException imme) {
System.out.println("enter correct value for age:");
in.nextInt(); // why this not works?
}
}
Enter Your age: hh
enter correct value for age:
Exception in thread "main" java.util.InputMismatchException
我想请求输入有效的int值,直到有效输入进入。
答案 0 :(得分:1)
如果nextInt()
无法将输入解析为int,则会将输入保留在缓冲区中。因此,下次调用nextInt()
时,它会尝试再次读取相同的垃圾值。在再次尝试之前,您必须致电nextLine()
吃垃圾输入:
System.out.print("Enter your age:");
try {
age = in.nextInt();
} catch (InputMismatchException imme) {
System.out.println("Enter correct value for age:");
in.nextLine(); // get garbage input and discard it
age = in.nextInt(); // now you can read fresh input
}
你可能也希望将它安排在循环中,这样只要输入不合适就会反复询问:
System.out.print("Enter your age:");
for (;;) {
try {
age = in.nextInt();
break;
} catch (InputMismatchException imme) {}
in.nextLine();
System.out.println("Enter correct value for age:");
}