首页 > 解决方案 > 为什么我的 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方法在我的代码中不起作用吗?

标签: javaloopswhile-looptry-catch

解决方案


ScannernextInt方法的javadoc声明它会抛出一个InputMismatchException. 不是一个NumberFormatException。(您与 混淆Integer.parseInt)。


推荐阅读