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
# 1 楼答案
好的,我一字不差地复制粘贴了你的代码,把它放在一个类中,导入
java.util.Scanner
并运行javac
。在我看来,你的文件末尾有两个额外的“}”。您还有其他问题:result4和result5没有初始化,编译器会对您发火,因为如果y==0为真,那么divide
和mod
方法的返回值就没有定义# 2 楼答案
这是因为当你除以0时,Java会抛出一个异常。如果您只想使用If语句来处理它,那么可以使用以下方法:
Java还通过try/catch块处理异常,try/catch块在
try
块中运行代码,并将处理catch
块中异常的处理方式。所以你可以做: