Reputation: 1
I'm making a number verifier for a console game that uses recursion to ensure that the user eventually gives a valid input. But whenever I submit an invalid input I get an imminent wall of “That is not a valid input. Please try again: That is not a valid input. Please try again: That is not a valid input. Please try again:” Until a StackOverflowError occurs. What I'm guessing is happening is that the scanner isn't reading the console in recursions. But I don't understand why that would be happening.
private int getInt(int greatest, int least)
{
try
{
int output = scanner.nextInt();
if(output > greatest || output < least)
{
System.out.println("That is not a valid input. Please try again:");
return getInt(greatest, least);
}
return output;
} catch (Exception e)
{
System.out.println("That is not a valid input. Please try again:");
return getInt(greatest, least);
}
}
What I've tried so far is having the function close the scanner when it's done and using a parsed nextLine instead of nextInt.
Upvotes: -3
Views: 65