有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为什么我的代码会抛出算术异常,而我希望它只是打印“错误”?

我制作了一个程序,要求用户输入两个数字,如果第二个数字是0,它应该会给出一个错误。然而,我得到了一个错误,如下所示。我有一个if-else语句,但它没有达到我预期的效果。我不确定我做错了什么

public static void main(String[] args) {
    int x, y;
    Scanner kbd = new Scanner(System.in);

    System.out.print("Enter a: ");
    x = kbd.nextInt();
    System.out.print("Enter b: ");
    y = kbd.nextInt();

    int result = add(x, y);
    int result2 = sub(x, y);
    int result3 = multi(x, y);
    int result4 = divide(x, y);
    int result5 = mod(x, y);

    System.out.println(x + " + " + y + " = " + result);
    System.out.println(x + " - " + y + " = " + result2);
    System.out.println(x + " * " + y + " = " + result3);
    System.out.println(x + " / " + y + " = " + result4);
    System.out.print(x + " % " + y + " = " + result5);
}

public static int add(int x, int y) {
    int result;
    result = x + y;
    return result;
}

public static int sub(int x, int y) {
    int result2;
    result2 = x - y;
    return result2;
}

public static int multi(int x, int y) {
    int result3;
    result3 = x * y;
    return result3;
}

public static int divide(int x, int y) {
    int result4;
    result4 = x / y;
    if (y == 0) {
        System.out.print("Error");
    } else {
        result4 = x / y; 
    }
    return result4; 
}

public static int mod(int x, int y) {
    int result5;
    result5 = x % y;
    if (y == 0) {
        System.out.print("Error");
    } else {
        result5 = x % y;
    }
    return result5;
}

输出 我得到了这个错误

Enter a: 10
Enter b: 0
Exception in thread "main" java.lang.ArithmeticException: / by zero

共 (2) 个答案

  1. # 1 楼答案

    好的,我一字不差地复制粘贴了你的代码,把它放在一个类中,导入java.util.Scanner并运行javac。在我看来,你的文件末尾有两个额外的“}”。您还有其他问题:result4和result5没有初始化,编译器会对您发火,因为如果y==0为真,那么dividemod方法的返回值就没有定义

  2. # 2 楼答案

    这是因为当你除以0时,Java会抛出一个异常。如果您只想使用If语句来处理它,那么可以使用以下方法:

    public static int divide(int x, int y){
       int result;
       if ( y == 0 ) {
     // handle your Exception here
     } else {
       result = x/y; 
      }
      return result; 
    }
    

    Java还通过try/catch块处理异常,try/catch块在try块中运行代码,并将处理catch块中异常的处理方式。所以你可以做:

    try {  
           result4 = divide(a, b);
    }
    catch(//the exception types you want to catch ){
         // how you choose to handle it
    }