Try-Catch总和两个数字

时间:2016-05-11 21:18:20

标签: exception-handling try-catch

我正在处理异常处理并创建一个新的Java Project.Program等待来自键盘的用户类型2数字。如果用户键入两个整数,它将对这些数字求和。如果用户没有输入数字,程序将打印'类型编号!'在屏幕上。这是我试过的:

public static void main(String[] args) {
    int a = 0;
    int b = 0;
    System.out.println("Type two numbers");
    Scanner scan = new Scanner(System.in);
    try {
        a = scan.nextInt();
        b = scan.nextInt();
    } catch (Exception ex) {
        System.err.println("Type number!");
    }
}

1 个答案:

答案 0 :(得分:1)

请尝试以下代码。它应该按预期工作:

public static void main(String[] args) {
    System.out.println("Type two numbers");
    sum();
}

private static void sum(){
    int a = 0;
    int b = 0;
    Scanner scan = new Scanner(System.in);
    try {
        a = scan.nextInt();
        b = scan.nextInt();
        System.out.println(a+b);
    } catch (Exception ex) {
        System.err.println("Type numbers in correct format!");
        sum();
    }
}