异常处理的意外输出

时间:2015-02-21 21:31:54

标签: java

请告诉我我的代码有什么问题。在输入的两个输入都是整数之前,它应该要求输入

public static void main(String[] args) {
    int a, b;
    Scanner input = new Scanner(System.in);
    int i = 0;

    while (i == 0) {
        try {

            System.out.print("Enter first number");
            a = input.nextInt();
            System.out.println("The number you entered is " + a);
            System.out.println("Enter second number");
            b = input.nextInt();
            System.out.println("The number you entered is " + b);

            i++;
        } catch (InputMismatchException e) {
            e.printStackTrace();
        }
    }
    System.out.println("End");
}

2 个答案:

答案 0 :(得分:2)

如果输入了无效的整数,则内容将保留在输入缓冲区中,并无限制地传递到异常块。需要使用nextnextLine使用这些无效字符。在调用nextInt

之前,应使用hasNextInt来检查整数是否实际可用

答案 1 :(得分:-1)

您的循环条件是:

int i = 0;
while (i == 0) {  // Looping against i==0
    try {
        System.out.print("Enter first number");
        a = input.nextInt();
        System.out.println("The number you entered is " + a);
        System.out.println("Enter second number");
        b = input.nextInt();
        System.out.println("The number you entered is " + b);
        i++; // Increments the value of i to 1, which makes the loop to exit after first iteration
    } catch (InputMismatchException e) {
        e.printStackTrace();
    }
}

将您的代码重构为:

boolean areBothIntegers = true;
        while (areBothIntegers) {
            try {
                System.out.print("Enter first number");
                a = input.nextInt();
                System.out.println("The number you entered is " + a);
                System.out.println("Enter second number");
                b = input.nextInt();
                System.out.println("The number you entered is " + b);
            } catch (InputMismatchException e) {
                e.printStackTrace();
                areBothIntegers = false;
            }
        }

示例输出:

输入第一个数字:10

您输入的数字是10

输入第二个数字:21

您输入的数字是21

输入第一个数字:21

您输入的数字是21

输入第二个数字:34

您输入的数字是34

输入第一个数字:21.5 //不是int值,因此抛出异常并退出

java.util.InputMismatchException
    at java.util.Scanner.throwFor(Scanner.java:909)
    at java.util.Scanner.next(Scanner.java:1530)
    at java.util.Scanner.nextInt(Scanner.java:2160)
    at java.util.Scanner.nextInt(Scanner.java:2119)
    at jdbc.statements.ADS.main(ADS.java:15)