java - 为什么即使我有一个 catch 语句,我仍然会收到 InputMissmatchException
问题描述
System.out.print("What kind of array do you want to create?\n1. Integer Array\n2. Double Array\n3. String Array\nYour Answer: ");
String input;
int num1 = 0;
try {
input = s.next();
num1 = Integer.parseInt(input);
while (num1 > 3 || num1 < 1) {
System.out.print("Please enter one of the three available options.\nYour Answer: ");
input = s.next();
num1 = Integer.parseInt(input);
}
} catch (InputMismatchException e) {
System.out.println("Do not enter a letter/special character");
}
所以我基本上是在向用户提出一个问题,询问他想要创建什么样的数组。但是,当我尝试打破它并放入Char
/时String
,直到出现错误并且程序退出。
解决方案
在 while 循环中添加 try-catch 块。否则,异常会在循环之后被捕获,并且当您处理异常(在 catch 块中)时,您会继续流程而不要求用户重试。
不过,这不是导致您的问题的原因。如果您只想打印错误并继续,那么您应该将代码切换到nextInt()
而不是next()
and parseInt()
。那么异常就会是正确的,并且会更容易阅读。(目前,NumberFormatException
当您尝试将 String 解析为 Int 而不是输入异常时,您可能会得到 - 如果您想这样做,请更改您尝试捕获的异常)
int num1 = 0;
try {
num1 = s.nextInt();
while (num1 > 3 || num1 < 1) {
System.out.print("Please enter one of the three available options.\nYour Answer: ");
num1 = s.nextInt();
}
} catch (InputMismatchException e) {
System.out.println("Do not enter a letter/special character");
}
推荐阅读
- c# - 使用 C# 在 ASP.NET 服务器上保存图像时出现“GDI+ 中发生一般错误”
- python - 如何将字符串从输入转换为整数?(Python 3.9)
- enums - 不能在其枚举类声明之外 OR 2 个相同类型的枚举值
- rust - 在 nom 6.2.1 中创建错误以匹配 nom::IResult
- python - 如何从 Python 中的虚拟变量中很好地绘制决策树?
- virtual-machine - 访问托管在云虚拟机上的应用程序
- html - 从引用 Django 模板的 href 属性中删除下划线
- python - 控制台中的 Pycharm url 丢失
- html - 在轮播中调整图像大小
- python - 将单元格转换为原始的 IPython 单元格魔术