0

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;
}
4
  • Your code, unmodified, doesn't have any infinite loop. The method will return the value as soon as it's bigger than than or equal to the min value. Commented Sep 7, 2019 at 6:46
  • Ok, thanks for that. So nothing needs to be in the catch block ie. min - 1? If I enter an invalid data type eg. "abc" my program will continue to output the prompt over and over instead of getting user the user input again. Commented Sep 7, 2019 at 7:07
  • Oh, sorry, I misread. I thought you were saying that it didn't work when you entered valid integer values. Commented Sep 7, 2019 at 7:10
  • No worries, thanks for your help. Commented Sep 7, 2019 at 7:19

1 Answer 1

1

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.

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

1 Comment

Great thanks that worked. Saved me a lot of time! Cheers.

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.