Clement Hoang
Clement Hoang

Reputation: 675

Java stuck in an infinite loop when using Try/Catch

For a project in school, I am attempting to use the try/catch to prevent the program from crashing when the user enters a letter instead of the desired input type (i.e. a double).

    public static double inputSide () {
    Scanner in = new Scanner(System.in);
    double side = -1;
    do {
        try {
        System.out.println("Enter a side length (in units):");
        side = in.nextDouble();
        }
        catch(InputMismatchException e){
            System.out.println("Must input number");

            }
    } while (side < 0);
    return side;
}

When I execute this code, it gets stuck in a loop where it outputs "Enter a side length (in units): " and "Must input number" infinitely. I am new to using try/catch, so I perhaps am simply unfamiliar with this behaviour. Anyway, if someone can help me figure out the problem, it would be much appreciated. Thanks in advance.

Upvotes: 3

Views: 3407

Answers (1)

BackSlash
BackSlash

Reputation: 22233

You have to free the buffer if you have a wrong input, in the catch block add this line:

in.next();

And everything should work:

public static double inputSide () {
    Scanner in = new Scanner(System.in);
    double side = -1;
    do {
        try {
            System.out.println("Enter a side length (in units):");
            side = in.nextDouble();
        }
        catch(InputMismatchException e){
            System.out.println("Must input number");
            //this line frees the buffer
            in.next();
        }
    } while (side < 0);
    return side;
}

In future, consider using

if(in.hasNextDouble()){
    //read
}

instead of a try-catch block

Upvotes: 4

Related Questions