Java try catch问题

标签 java exception try-catch

我试图用这段代码完成的任务是检查用户的输入是否为整数,然后如果数据类型不正确,则给他们 3 次再次输入的机会。如果达到“maxTries”标记,最后抛出异常。

任何帮助将不胜感激。干杯。

    boolean correctInput = false;    
    int returnedInt = 0;
    int count = 0;
    int maxTries = 3;

    Scanner kybd = new Scanner(System.in); 

    while(!correctInput)
    {
        try 
        {   
            System.out.println("\nInput your int, you have had:" + count + " tries");
            returnedInt = kybd.nextInt();
            correctInput = true;

        }
        catch(InputMismatchException e)
        {
            System.out.println("That is not an integer, please try again..");   
            if (++count == maxTries) throw e;

        }

    }
    return returnedInt;

最佳答案

发生这种情况的原因是您的扫描仪缓冲区未清除。输入 kybd.nextInt() 已填充非 int,但由于读取失败,因此实际上并未将其从堆栈中删除。因此,第二个循环它尝试再次拉出已填充的缓冲区,这已经是错误的了。

要解决此问题,您可以在异常处理中使用 nextLine() 清除缓冲区。

        } catch (InputMismatchException e) {
            System.out
                    .println("That is not an integer, please try again..");
            kybd.nextLine(); //clear the buffer, you can System.out.println this to see that the stuff you typed is still there
            if (++count == maxTries)
                throw e;

        }

另一种选择是使用 String s = kybd.nextLine() 并解析 Integer 并从中捕获异常。

关于Java try catch问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26471387/

相关文章:

java - if/then 与像素查找和循环,所有这些目前都在我之上

java - 如何在vaadin中关闭窗口?

eclipse - 从 diskfileupload 上传文件时出错

python - 为什么列表没有像字典一样的安全 "get"方法?

javascript - 如何在 es6 版本的 javascript 中使用 java 库?

java - 年轻代的大小将如何调整?

exception - 在 Windows 事件查看器中诊断 CLR 错误

Scala try-catch没有捕获异常

java - 捕获非抛出的检查异常

Java try..catch 和finally