Reputation: 757
I'm trying to make a function that checks for an integer and will keep looping until the user correctly enters an integer of 17 or higher. However, if I put in wrong input, like 'K', or '&', it will get stuck in an infinite loop.
public static int getAge(Scanner scanner) {
int age;
boolean repeat = true;
while (repeat) {
try
{
System.out.println("Enter the soldier's age: ");
age = scanner.nextInt();
repeat = false;
}
catch(InputMismatchException exception)
{
System.out.println("ERROR: You must enter an age of 17 or higher");
repeat = true;
}
}
return age;
}
Upvotes: 1
Views: 6414
Reputation: 4592
If next available input token isn't an integer, nextInt()
leaves that input unconsumed, buffered inside the Scanner
. The idea is that you might want to try to read it with some other Scanner
method, such as nextDouble()
. Unfortunately, this also means that unless you do something to get rid of the buffered-up garbage, your next call to nextInt()
will will just try (and fail) to read the same junk over again.
So, to flush out the junk, you need to call either next()
or nextLine()
before trying to call nextInt()
again. This ensures that the next time you call nextInt()
, it will have new data to work on instead of the same old garbage:
try {
//...
}
catch(InputMismatchException exception)
{
System.out.println("ERROR: You must enter an age of 17 or higher");
scanner.next(); // or scanner.nextLine()
repeat = true;
}
Upvotes: 2
Reputation: 11
I would not pass a scanner to your method I would try re structuring it, and assigning the method to a variable in your main like this:
I am also using recursion in my catch to recall the method when the exception is caught, id also recommend using maybe a general exception , making it catch(Exception exception)
main method call of method
---------------------------
int something= getAge();
----------------------------------------------------------
method structure like this,
---------------------------------------------
public static int getAge() {
int age;
age = scanner.nextInt();
boolean repeat = true;
while (repeat) {
try
{
System.out.println("Enter the soldier's age: ");
if(age<=17){
repeat = false;
}
if(age>17){
getAge();
}
}
catch(InputMismatchException exception)
{
System.out.println("ERROR: You must enter an age of 17 or higher");
getAge();
}
}
return age;
}
<!-- end snippet -->
Upvotes: 0