Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java stuck in an infinite loop when using Try/Catch

Tags:

java

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.

like image 312
Clement Hoang Avatar asked Apr 13 '26 22:04

Clement Hoang


1 Answers

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

like image 64
BackSlash Avatar answered Apr 16 '26 12:04

BackSlash



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!