Why doesn't this method of getting user input work?
I have the following code which I'm using to get the user to input an integer, check to make sure the input is valid, and if not, ask for input again. When the code is run, everything works fine until some invalid input is given, at which point the code loops without pausing to ask for input again until a stack overflow occurs, and I have no idea why. The code:
//Create the scanner object
private static Scanner in = new Scanner(System.in);
//Function to get input in integer form, complete with exception handling
//A value of -1 means the user is done inputing
public static int getInt()
{
int num;
//Begin try block
try
{
//Get the user to input an integer
num = in.nextInt();
//Make sure the integer is positive. Throw an exception otherwise
if (num < -1)
throw new InputMismatchException();
}
//If an exception occurred during the inputting process, recursively call this function
catch (InputMi开发者_开发百科smatchException e)
{
System.out.println("Error: Input must be a positive integer, or -1.");
System.out.print("Enter a score: ");
num = getInt();
}
//Return the inputed number
return num;
}
When a scanner throws an InputMismatchException, the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method
So sayeth the javadoc, i.e. the string that is not a number is not removed from the input automatically. Call in.next() manually to discard it.
You should call next();
to skip the invalid input before calling nextInt();
once more.
Is it necessary for the function to be recursive? Seems like this should be easy enough to do with a simple loop.
getInt() -> if (num<-1) throw Exception() -> catch (exception) -> num = getInt()
how do you expect NOT to loop ?
精彩评论