0

I am creating a program that takes input from the user.Now I want to re-run the input option if a user enters an invalid command. Like here only integer input are preferred but if the user inputs text, then I want to catch the exception and rerun the method.

I have tried this but it turns me into an infinite loop.What would be the best way to achieve this. It would be great if someone helps me on this.

    boolean retry = true;

    while(retry){

        try{
            //considering response from the user
            System.out.print("\nEnter Your Command : ");
             f_continue =  processresponse(scanner.nextInt());
             retry = false;
        }catch(InputMismatchException e){

            System.err.println("\nPlease Input a Valid Command from 1-5 or 0 for Exit");




        }

    }
1

1 Answer 1

1

If you enter something other than an integer, nextInt() will throw an exception, and what was entered will still be in the input buffer, so the next time you call nextInt(), you will read the same bad input. You should first call hasNextInt() to see if the input is an integer; if not, just call nextLine() to skip the bad input (and write a message telling the user to re-try).

Or you can just call scanner.nextLine() in the catch block.

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

Comments

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.