My code below occur this error when I typed letter instead of number.
import java.util.Scanner;
public class ExceptionExample {
public static void main(String[] args) {
Scanner number = new Scanner(System.in);
int x = 1;
do {
try {
int n1, n2;
System.out.println("Enter the firs num");
n1 = number.nextInt();
System.out.println("Enter the second num");
n2 = number.nextInt();
int sum = n1 / n2;
System.out.println(sum);
x = 2;
} catch (Exception e) {
System.out.println("You can not do that\n");
}
} while (x == 1);
}
}
When I entered the letter, I expected to get just one line of "You can not do that" but it shows me infinite loop like this.
Enter the firs num
You can not do that
Enter the firs num
You can not do that
Enter the firs num
You can not do that
.
.
.
if anyone knows why does this happen?