Why I\'m getting infinite loop in recursion method, without a chance to input any symbol to break it?
class Test {
int key=0;
void meth(){
System.out.
If nextInt()
fails, it throws an exception but doesn't consume the invalid data. From the documentation:
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.
You're then recursively calling meth()
again, which will try to consume the same invalid data a second time, fail again (without consuming it), and recurse.
Firstly, I wouldn't use recursion here in the first place. Prefer a simple loop. Next, if you have invalid input you should consume it appropriately before trying again. Finally, consider using hasNextInt
instead of just using nextInt
and catching the exception.
So maybe something like this:
import java.util.Scanner;
class Test {
public static void main(String[] args){
try (Scanner scanner = new Scanner(System.in)) {
System.out.println("Enter the number here:");
while (!scanner.hasNextInt() && scanner.hasNext()) {
System.out.println("Error");
// Skip the invalid token
scanner.next();
}
if (scanner.hasNext()) {
int value = scanner.nextInt();
System.out.println("You entered: " + value);
} else {
System.out.println("You bailed out");
}
}
}
}