继续从捕获块中的扫描仪获取信息

Continue to get info from scanner in catch block

我只是想为 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 值,直到输入一个有效的输入。

如果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:");
}