I am trying to get an integer from a user using a scanner and an infinite loop. I know a solution to solve this problem, but I keep wondering why my first approach is not working properly?
Scanner myScanner = new Scanner(System.in);
int x = 0;
while(true){
try{
System.out.println("Insert a number: ");
x = myScanner.nextInt();
break;
}catch(InputMismatchException e){
System.out.println("Invalid, try again.");
continue;
}
}
It works on the first iteration, but then it just keeps the “Invalid, try again” print on the screen forever.
source
share