Richard
Richard

Reputation: 5

Do while and try catch stuck in loop for user input validation/exception handling

I'm trying to figure out what's wrong with my code. I can't re-enter into the try block and ask the user to input again.

Commented out are a few things which I've already tried. But nothing has worked. Sometimes will get stuck in infinite loop. Thanks for your help!

public static int integerInput(String prompt,int min) {
    int value;
    String error, outStr;
    Scanner sc = new Scanner(System.in);

    value  = min - 1;
    error = "ERROR value must be above " + min;
    outStr = prompt;
    do {
        try {
            System.out.println(outStr);
            value = sc.nextInt();
            outStr = error + "\n" + prompt;
        }
        catch (Exception e) {
            //value = -1;
            //outStr = "ERROR input must be of type int" + "\n" + prompt;
            //value = -1;
            //value = sc.nextInt();
        }
        //value = - 1;

    }while (value < min);

    return value;
}

Upvotes: 0

Views: 368

Answers (1)

Rumid
Rumid

Reputation: 1709

Currently your program is reading constantly the same line, that's why it stuck on do - while. It is reading the same line, because on exception

the scanner's input cursor is reset to where it was before the call.

If you want it to move to another line add sc.nextLine(); in your catch block.

About your attempt in catch block - your program again is reading the same line, but this time it is not in try block, so the same exception is thrown (InputMismatchException) and program stops. I would suggest you to catch this exactly exception instead of Exception.

Upvotes: 1

Related Questions