为什么会发生这种错误?

时间:2018-01-14 21:38:57

标签: java

当我输入字母而不是数字时,下面的代码会出现此错误。

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);

    }
}

当我输入这封信时,我希望得到一行“你不能那样做”,但它向我展示了这样的无限循环。

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
.
.
.

如果有人知道为什么会这样?

0 个答案:

没有答案