Reputation: 125
I am trying to find the multiples of the numbers being inputted, but every time the user enters 0 i get this error.
Exception in thread "main" java.lang.ArithmeticException: / by zero
Yes i know that you cant divide by zero but there has to be a way to make this work.
This is suppose to still work even with the zero being inputted.
public static int prob1Rec(int num1, int num2) {
int sum = 0;
for (int i = 1; i < 500; i++) {
if ((i % num1 == 0) || (i % num2 == 0)) {
sum += i;
}
}
return sum;
}
Note: If one of the numbers is zero, i still want to add up the multiples of the other number.
Upvotes: 0
Views: 102
Reputation: 425198
The expression i % num1
performs a division, so your code is not safe.
Add this line as the first line of your method:
if (num1 == 0 || num2 == 0)
return 0;
Upvotes: 0
Reputation: 79847
You could change the if
to
if ((num1 != 0 && i % num1 == 0) || (num2 != 0 && i % num2 == 0)) {
Upvotes: 1