Troube Looping "try/catch"
When I run the below method and intentionally input a letter when a number is expected, I get a never-ending loop that doesn't prompt for more input. Why?
Code :
private static int intInput() //Asks the user for an int and returns the input.
{
Scanner genericIntScan = new Scanner(System.in);
boolean itsAnInt = false;
int genericInt = 0;
while(itsAnInt==false)
{
try
{
genericInt = genericIntScan.nextInt();
itsAnInt = true;
}
catch(InputMismatchException ime)
{
System.out.println("\nYou're supposed to type in a number. Try again.");
itsAnInt = false;
}
}
return genericInt;
}
Re: Troube Looping "try/catch"
Hello joelamos!
What do you want it to do instead of "repeating"?
When the exception occurs you have the following statement itsAnInt = false; So the while loop keeps going.
Re: Troube Looping "try/catch"
What I meant by "repeating" was "never-ending". After it executes the catch lines, shouldn't it go back to "try" and prompt for more input instead of continually repeating the catch lines?
Re: Troube Looping "try/catch"
Quote:
Originally Posted by
joelamos
What I meant by "repeating" was "never-ending". After it executes the catch lines, shouldn't it go back to "try" and prompt for more input instead of continually repeating the catch lines?
You can avoid the infinite loop if you create the Scanner oblect inside the try clause.
Re: Troube Looping "try/catch"
You need to read the bad input and clear the Scanner's input buffer so the next call to nextInt() will have fresh data. Also you could use one of the has... methods to test if the next input is the correct type.