java - Trying to prompt the user to re-enter from the catch block, but the catch block terminates?
问题描述
I am trying to write a program to ask a user to enter their age and prompt them to re-enter if they enter an improper value (such as a negative number, older than 120, an age with special characters or letters, an out of range number etc...)
I tried writing a try/catch to ask the user to re-enter their age:
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();
}
When the age entered contains special characters/letters or is out of range, the program DOES print out the words "Bad age. Re-enter your age (a positive integer)," however it immediately terminates thereafter with this error:
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)
My goal is to get the program to continue prompting for a valid age until the user gets its right. I would really appreciate any feedback and help. I am a java beginner :) Thank you
I tried to change put the whole code into a while loop but then it causes an infinite loop... please help!
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
应将其封装在loop
验证过程中。
使用 读取输入时nextInt
,不会删除无效输入,因此您需要确保在尝试使用 重新读取之前清除缓冲区nextLine
。或者你可以放弃它,直接读取String
using 的值nextLine
,然后将其转换为int
using Integer.parseInt
,这对个人而言比较不麻烦。
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
循环,基本上是因为,即使是第一次传递的有效值,您也必须至少迭代一次
推荐阅读
- php - 当我将我的项目上传到在线模式时,在登录 TokenMismatchException Laravel
- java - Android:当 Context 对象不允许 Parcelable 时,我应该如何在活动之间传递 ListView?
- .htaccess - 基于协议限制对目录的访问
- wordpress - 将所有子网址重定向到父页面
- for-loop - 对于表中的行,将行保存在临时表中以在 plpgsql 的选择查询中使用其数据
- azure - Azure 备份 - 文件系统一致、应用程序一致和崩溃一致
- php - 在 laravel 中从 UTC 时区将数据显示到 EST 时区
- r - 将文件名写入列标题
- python - 为什么我不能从 python 的类中导入函数?
- ios - iOS 动态表格视图周围有一个边框