So, I’m getting stuck with this piece of code:
import java.util.InputMismatchException;
import java.util.Scanner;
public class ConsoleReader {
Scanner reader;
public ConsoleReader() {
reader = new Scanner(System.in);
//reader.useDelimiter(System.getProperty("line.separator"));
}
public int readInt(String msg) {
int num = 0;
boolean loop = true;
while (loop) {
try {
System.out.println(msg);
num = reader.nextInt();
loop = false;
} catch (InputMismatchException e) {
System.out.println("Invalid value!");
}
}
return num;
}
}
and here is my output:
Insert a integer number:
Invalid value!
Insert a integer number:
Invalid value!
…
As per the javadoc for Scanner:
That means that if the next token is not an
int, it throws theInputMismatchException, but the token stays there. So on the next iteration of the loop,reader.nextInt()reads the same token again and throws the exception again. What you need is to use it up. Add areader.next()inside yourcatchto consume the token, which is invalid and needs to be discarded.