I'm trying to only allow an integer input and stop my programm from breaking when something else is entered. Somehow my code creates an endless loop and doesn't let me enter a new input.
private static int x;
public static void main(String[] args) {
testInput();
}
public static void testInput(){
while (true){
System.out.println("Please enter Integer:");
try{
setX(scanner.nextInt());
break;
}catch (InputMismatchException i){
System.out.println("Please use Integer");
}
}
}
public static void setX(int integer){
x = integer;
}
}
Creates endless loop which says: Please enter Integer: , Please use Integer instead of letting me make new input.
scanner.nextInt()doesn't consume the token if it's not an integer. I'd personally be tempted to avoidScannerentirely, and just read lines fromSystem.ininstead. I've seen a lot of questions aboutScannerthat basically show it's a hard to use API.