java - 为什么我的 try catch 方法没有显示我为输入的字符串而不是整数编写的错误消息?(爪哇)
问题描述
System.out.println(" ");
System.out.println("Stage 4: Enter an integer between 5 and 500:");
IntEntry = keyedInput.nextInt();
if(IntEntry > 5 && IntEntry < 500)
{
System.out.println("You will go to stage 5.");
}
else
{
try
{
while(IntEntry < 5 || IntEntry > 500)
{
System.out.println("Try Again. Enter an integer that is between 5 and 500 characters long. “z”.");
IntEntry = keyedInput.nextInt();
}
}
catch(NumberFormatException e)
{
System.out.println("Try Again. Enter an integer between 5 and 500:.");
}
}
以上是我试图获取用户输入的介于 5 和 500 之间的有效整数的代码。如果用户输入的是字符串而不是整数,程序应该使用try-catch方法为用户输出一条消息. try-catch方法对我不起作用,它会输出一条错误消息。有人能告诉我为什么try-catch方法在我的代码中不起作用吗?
解决方案
ScannernextInt
方法的javadoc声明它会抛出一个InputMismatchException
. 不是一个NumberFormatException
。(您与 混淆Integer.parseInt
)。
推荐阅读
- reactjs - undefined 不是函数(在'....data.map....'附近)|React native
- python - 在 jupyter notebook 中运行带有超时的 python 脚本
- java - Android导航抽屉没有打开新的活动
- java - 如何将 TypeScript 日期转换为 Java 日期
- python - 从我的用户关注的用户那里获取所有帖子
- node.js - 无法解析带有双 apix 的字符串
- node.js - Docker 应用程序将无法工作,但如果不在 Docker 中,应用程序可以工作
- spring-boot - 使用 JPA 进行实体设计
- firebase - 如何在使用 Firebase 和 Flutter 登录和注册时发现身份验证错误?
- django - 保护 Django API 的最佳方法是什么?