validation - How to retry a method after an exception in java? -


i creating program takes input user.now want re-run input option if user enters invalid command. here integer input preferred if user inputs text, want catch exception , rerun method.

i have tried turns me infinite loop.what best way achieve this. great if helps me on this.

    boolean retry = true;      while(retry){          try{             //considering response user             system.out.print("\nenter command : ");              f_continue =  processresponse(scanner.nextint());              retry = false;         }catch(inputmismatchexception e){              system.err.println("\nplease input valid command 1-5 or 0 exit");             }      } 

if enter other integer, nextint() throw exception, , entered still in input buffer, next time call nextint(), read same bad input. should first call hasnextint() see if input integer; if not, call nextline() skip bad input (and write message telling user re-try).

or can call scanner.nextline() in catch block.


Comments

Popular posts from this blog

javascript - Thinglink image not visible until browser resize -

firebird - Error "invalid transaction handle (expecting explicit transaction start)" executing script from Delphi -

mongodb - How to keep track of users making Stripe Payments -