3

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.

0

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you very much! I'm looking into the in.hasNextDouble() method as we speak.
@ClementHoang You're welcome! Take a look at java.util.Scanner API, you'll see that there are a lot of Scanner#hasNextWhatever() for every data type, so you don't need a try-catch block. I don't remember if it also requires buffer-freeing if your input is wrong, if it goes through an infinite loop it is the same problem as try-catch, and you solve it with my answer! If it is the best for you, please "tick" it by clicking on the "V" symbol at the left of the answer :)
For anyone else reading. This happens because when the exception is called the scanner does not move to the next input token, Instead it tries to read it again. Adding the non data type specific .next() moves on to the next token.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.