Java Scanner exception handling

前端 未结 4 1785
挽巷
挽巷 2020-12-18 12:20

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

相关标签:
4条回答
  • 2020-12-18 12:57

    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.

    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.

    0 讨论(0)
  • 2020-12-18 13:04

    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. Try debugging the program for a better view.

    0 讨论(0)
  • 2020-12-18 13:06

    This method keeps on executing the same input token until it finds a line separator i.e. input.nextLine() or 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();
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-18 13:12

    The reason is that it keeps reading the same value over and over, so ending in your catch clause every time.

    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();
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题