【发布时间】:2015-07-15 04:09:07
【问题描述】:
我编写了一个程序,要求用户输入两个数字,如果第二个数字是 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
【问题讨论】:
-
那么这个错误是什么时候出现的呢?当你
divide(强调除)? -
它被称为“系统”而不是“系统”
-
你能粘贴你所有的文件吗?
-
开括号和右括号一样多吗?
-
是的,我相信对于每个左大括号都有一个右大括号,或者这是缺少大括号的唯一可能错误?
标签: java exception operators divide-by-zero