Im trying to create a simple program where user enters an integer and if its not an integer it prints that an error occured and the program loops until user enters an integer. I found this try-catch solution but it doesn`t work properly. If user doesnt enter an integer the program will infinitly loop.
What would the correct solution be?
Scanner input = new Scanner(System.in);
int number;
boolean isInt = false;
while(isInt == false)
{
System.out.println("Enter a number:");
try
{
number = input.nextInt();
isInt = true;
}
catch (InputMismatchException error)
{
System.out.println("Error! You need to enter an integer!");
}
}