尝试捕获两个数字之和

问题描述 投票:0回答:2

我正在研究异常处理并制作一个新的Java项目。程序等待用户从键盘输入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!");
    }
}
exception try-catch
2个回答
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();
    }
}

0
投票
public class Errors {
    public static void main(String[] args) {
        
        System.out.println("Enter an Integer Value for addition:-");
        Scanner sc = new Scanner(System.in);
        int user = 0;
        int user2 = 0;
        try {
            System.out.println("Enter value A");
            user = sc.nextInt();
            try {
                System.out.println("Enter value B");
                user2 = sc.nextInt();
                System.out.println(user+user2);
            }catch (Exception e){
                System.err.println("Please enter an Integer Value");
            }
        }catch(Exception e){
            System.err.println("Please enter an Integer value ");
        }

    }
}
© www.soinside.com 2019 - 2024. All rights reserved.