I tried to make a try-catch block in a program but when an exception occurs, it doesn't do what I intended
int num = 0;
boolean noException;
Scanner keyboard = new Scanner(System.in);
while (true)
{
noException = true;
System.out.print("Enter a number or 0 to exit: ");
try
{
num = keyboard.nextInt();
}
catch (InputMismatchException e)
{
noException = false;
System.out.println("\nNot a valid integer");
}
if (noException)
{
//rest of program (there is a break in here to exit)
}
}
It works fine when there is no exception, but
when I enter something that gives an exception, like "1.1"
it keeps printing constantly :
*Enter a number or 0 to exit:
Not a valid integer *
It seems to be skipping the try statement, I'm not sure why.