I have made a program that asks the user to enter two numbers, and it should give an error if the second number is a 0. However, I am getting an error, which is below. I have an if-else statement but it's not doing what I expect it to. I'm not sure what I'm doing wrong.
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;
}
Output I get this error..
Enter a: 10
Enter b: 0
Exception in thread "main" java.lang.ArithmeticException: / by zero