Java扫描器异常处理 [英] Java Scanner exception handling

查看:148
本文介绍了Java扫描器异常处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从用户那里收到一个Double,并处理抛出的异常,以防用户没有输入double / int;在这种情况下,我想要求用户再次插入金额。
如果异常被捕获,我的代码被卡在一个循环中,并且继续打印插入金额。

I would like to receive a Double from the user and handle the exception thrown in case the user didn't input a double/int; in that case I'd like to ask the user to insert the amount again. My code gets stuck in a loop if the exception is caught, and keeps printing "Insert amount".

    private static double inputAmount() {
    Scanner input = new Scanner(System.in);
    while (true) {
        System.out.println("Insert amount:");
        try {
            double amount = input.nextDouble();
            return amount;
        }catch (java.util.InputMismatchException e) {continue;}
        }
    }

提前谢谢。

推荐答案

当遇到无效输入时,程序进入无限循环,因为 nextDouble() does 使用无效令牌。所以引起异常的任何令牌都会停留在那里,并且在下次尝试读取一个double时会继续引起异常。

Your program enters an infinite loop when an invalid input is encountered because nextDouble() does not consume invalid tokens. So whatever token that caused the exception will stay there and keep causing an exception to be thrown the next time you try to read a double.

这可以通过放置一个 nextLine() next()调用 catch 阻止消耗任何输入导致异常被抛出,清除输入流并允许用户再次输入。

This can be solved by putting a nextLine() or next() call inside the catch block to consume whatever input was causing the exception to be thrown, clearing the input stream and allowing the user to input something again.

这篇关于Java扫描器异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆