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");




        }

    }
Stephen C
  • 632,615
  • 86
  • 730
  • 1,096
  • You can read more about handling scanner input here: http://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo – azurefrog Sep 12 '16 at 21:48

1 Answers1

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.

sidgate
  • 11,396
  • 8
  • 53
  • 100
FredK
  • 4,036
  • 1
  • 6
  • 11