Java while loop endlessly catching mismatch exception -
i'm trying create simple while loop in java asks user number , stores in variable. i'm checking make sure value entered number. loop should tell user did not enter number if entered string. should ask user enter number again after tells them didn't enter number.
at moment code endlessly catches exception if user input string. how loop work?
scanner reader = new scanner(system.in); isint = false; while(!isint){ try{ system.out.println("enter number"); int anumber = reader.nextint(); isint = true; } catch(inputmismatchexception e){ system.out.println("you didn't enter number"); } }
the nextint() method not consuming non-numeric input. method's javadocs refer overloaded method nextint(int), states:
scans next token of input int. method throw inputmismatchexception if next token cannot translated valid int value described below. if translation successful, scanner advances past input matched.
(emphasis mine)
in catch block, add line calls reader.next() consume (and ignore) non-numeric input, next token can examined in next iteration of while loop.
Comments
Post a Comment