Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Scanner exception handling

Tags:

java

exception

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;}
        }
    }

Thank you in advance.

like image 425
Airwavezx Avatar asked Jun 25 '14 16:06

Airwavezx


2 Answers

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.

like image 141
awksp Avatar answered Oct 28 '22 20:10

awksp


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();
        }
    }
}
like image 42
Fradenger Avatar answered Oct 28 '22 20:10

Fradenger