简体   繁体   English

Java Scanner异常处理

[英]Java Scanner exception handling

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;我想从用户那里接收一个 Double 并处理在用户没有输入 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;}
        }
    }

Thank you in advance.先感谢您。

Your program enters an infinite loop when an invalid input is encountered because nextDouble() does not consume invalid tokens.你的程序进入,当输入无效,是因为遇到了一个无限循环nextDouble()消耗无效令牌。 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.因此,导致异常的任何标记都将保留在那里,并在您下次尝试读取 double 时继续引发异常。

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.这可以通过在catch块中放置nextLine()next()调用来解决,以消耗导致抛出异常的任何输入,清除输入流并允许用户再次输入某些内容。

The reason is that it keeps reading the same value over and over, so ending in your catch clause every time.原因是它一遍又一遍地读取相同的值,因此每次都以 catch 子句结尾。

You can try this:你可以试试这个:

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

Its because after the exception is caught, its stays in the buffer of scanner object.这是因为异常被捕获后,它会留在扫描仪对象的缓冲区中。 Hence its keeps on throwing the exception but since you handle it using continue, it will run in a loop.因此它不断抛出异常,但由于您使用 continue 处理它,它将在循环中运行。 Try debugging the program for a better view.尝试调试程序以获得更好的视图。

This method keeps on executing the same input token until it finds a line separator ie input.nextLine() or input.next()此方法继续执行相同的输入标记,直到找到行分隔符,即input.nextLine()input.next()

Check out the following code查看以下代码

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)
        {
            input.nextLine();
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM