java - Why doesn't this method of getting user input work? -


i have following code i'm using user input integer, check make sure input valid, , if not, ask input again. when code run, works fine until invalid input given, @ point code loops without pausing ask input again until stack overflow occurs, , have no idea why. code:

//create scanner object private static scanner in = new scanner(system.in);  //function input in integer form, complete exception handling //a value of -1 means user done inputing public static int getint() {     int num;      //begin try block     try     {         //get user input integer         num = in.nextint();          //make sure integer positive. throw exception otherwise         if (num < -1)             throw new inputmismatchexception();     }      //if exception occurred during inputting process, recursively call function     catch (inputmismatchexception e)     {         system.out.println("error: input must positive integer, or -1.");         system.out.print("enter score: ");         num = getint();     }      //return inputed number     return num; } 

when scanner throws inputmismatchexception, scanner not pass token caused exception, may retrieved or skipped via other method

so sayeth javadoc, i.e. string not number not removed input automatically. call in.next() manually discard it.


Comments

Popular posts from this blog

android - Spacing between the stars of a rating bar? -

html - Instapaper-like algorithm -

c# - How to execute a particular part of code asynchronously in a class -