【问题标题】:Try-Catch sum two numbersTry-Catch 将两个数字相加
【发布时间】:2016-05-11 21:18:20
【问题描述】:

我正在处理异常并制作一个新的 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!");
    }
}

【问题讨论】:

  • 那么问题到底是什么?
  • 确切的问题是,如果用户不输入整数值,当我们想对这些数字求和时会发生错误。所以我没有写求和操作
  • 好的,但是你的问题是什么?您是在问如何打印 2 个数字的总和?

标签: exception-handling try-catch


【解决方案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();
    }
}

【讨论】:

  • 非常感谢,为什么要写private?static void sum前面没有关键字就可以了
  • 是的,私有是可选的。它不会对实际问题产生太大影响
猜你喜欢
  • 1970-01-01
  • 2016-04-18
  • 2010-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-02
  • 2014-08-24
  • 1970-01-01
相关资源
最近更新 更多