gpt4 book ai didi

java - 尝试提示用户从 catch block 重新输入,但 catch block 终止?

转载 作者:行者123 更新时间:2023-12-02 10:48:17 25 4
gpt4 key购买 nike

我正在尝试编写一个程序,要求用户输入年龄,如果输入不正确的值(例如负数、超过 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();
}

当输入的年龄包含特殊字符/字母或超出范围时,程序会打印出“错误年龄。重新输入您的年龄(正整数)”字样,但此后它会立即终止并出现以下错误:

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

最佳答案

由于您 try catch 无效的输入状态,同时仍提示用户输入正确的值,因此 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 循环,基本上是因为,即使在第一次传递时获得有效值,您也必须至少迭代一次

关于java - 尝试提示用户从 catch block 重新输入,但 catch block 终止?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52377181/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com