试图提示用户从 catch 块重新输入,但 catch 块终止?

Trying to prompt the user to re-enter from the catch block, but the catch block terminates?

我正在尝试编写一个程序来要求用户输入他们的年龄,并在他们输入不正确的值(例如负数、大于 120 岁、带有特殊字符的年龄或字母、超出范围的数字等...)

我试着写了一个 try/catch 来要求用户重新输入他们的年龄:

System.out.println("Enter your age (a positive integer): ");
    int num;

    try {
        num = in.nextInt();
        while (num < 0 || num > 120) {
            System.out.println("Bad age. Re-enter your age (a positive integer): ");
            num = in.nextInt();
        }
    } catch (InputMismatchException e) {
        //System.out.println(e);
        System.out.println("Bad age. Re-enter your age (a positive integer): ");
        num = in.nextInt();
    }

当输入的年龄包含特殊的 characters/letters 或超出范围时,程序会打印出 "Bad age. Re-enter your age (a positive integer)," 字样,但此后它会立即终止并出现此错误:

Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Unknown Source)
at java.base/java.util.Scanner.next(Unknown Source)
at java.base/java.util.Scanner.nextInt(Unknown Source)
at java.base/java.util.Scanner.nextInt(Unknown Source)
at Age.main(Age.java:21)

我的目标是让程序继续提示有效年龄,直到用户获得正确的年龄。 我真的很感激任何反馈和帮助。我是 java 初学者 :) 谢谢

我试图将整个代码更改为 while 循环,但随后导致无限循环...请帮忙!

while (num < 0 || num > 120) {
        try {
            System.out.println("Bad age. Re-enter your age (a positive integer): ");
            num = in.nextInt();
        } catch (InputMismatchException e) {
            System.out.println("Bad age. Re-enter your age (a positive integer): ");
        }
    }

即使您能够提示用户重新输入他的年龄,您之后也无法检查输入是否正确。因此,我建议使用一个简单的 while 循环,就像您正在做的那样,但不要只查找一个数字范围,而是在尝试将其解析为 int 之前检查它是否是一个数字。

如果使用input.nextLine().trim();例如,您可以使用 StringUtils.isNumeric 之类的方法,或者您可以将自己的方法实现为 return 一个布尔值,指示输入是否为数字。

由于您试图捕获无效的输入状态,同时仍提示用户输入正确的值,因此 try-catch 应该封装在 loop 中作为其验证过程的一部分。

使用 nextInt 读取输入时,不会删除无效输入,因此您需要确保在使用 nextLine 尝试重新读取之前清除缓冲区。或者你可以放弃它,直接使用 nextLine 读取 String 值,然后使用 Integer.parseInt 将其转换为 int,就个人而言,这不那么麻烦。

Scanner scanner = new Scanner(System.in);
int age = -1;
do {
    try {
        System.out.print("Enter ago between 0 and 250 years: ");
        String text = scanner.nextLine(); // Solves dangling new line
        age = Integer.parseInt(text);
        if (age < 0 || age > 250) {
            System.out.println("Invalid age, must be between 0 and 250");
        }
    } catch (NumberFormatException ime) {
        System.out.println("Invalid input - numbers only please");
    }
} while (age < 0 || age > 250);

使用 do-while 循环,主要是因为,您必须至少迭代一次,即使是在第一遍中获得有效值