Reputation: 43
My program should print out all three digit numbers which are divisible by its own figures for example 124 is divisible by 1, 2 and 4, it also should ignore all numbers with an 0 in it like 120 130 208 etc. If I try to compile it in eclipse it just stops at 184 and I have no clue why. I'm a beginner at coding and sorry for bad English.
public class Teilbarkeitlol {
public static void methode() {
for (int zahl = 111; zahl <= 999; zahl++) {
if (zahl % 10 == 0) {
} else {
int dig1 = zahl / 100;
int dig2 = (zahl % 100) / 10;
int dig3 = zahl % 10;
if (zahl % dig1 == 0 && zahl % dig2 == 0 && zahl % dig3 == 0) {
System.out.println(zahl);
} else {}
}
}
}
public static void main(String[] args) {
methode();
}
}
Upvotes: 1
Views: 161
Reputation: 581
if (zahl % dig1 == 0 && zahl % dig2 == 0 && zahl % dig3 == 0) {
In this line when either dig1 or dig2 or dig3 becomes zero, your code is trying to do a division by zero operation. This happens at 201.
201%0
this gives an exception and your code stops at that point. (until that point your code skips those divisions by zero by skipping values divided by 10 :) ex: 120, 130 )
Solution would be check if dig1 or dig2 or dig3 is zero before performing that operation.
Also the blank if and else tags are not needed (not wrong either :))
else {
}
Upvotes: 1
Reputation: 176
Your code is throwing java.lang.ArithmeticException: / by zero because your "should ignore all numbers with an 0" part is incorrect. You can also do it by converting a number to String and checking of accourance.
for (int zahl = 111; zahl <= 999; zahl++) {
if (!Integer.toString(zahl).contains("0")) {
int dig1 = zahl / 100;
int dig2 = (zahl % 100) / 10;
int dig3 = zahl % 10;
if (zahl % dig1 == 0 && zahl % dig2 == 0 && zahl % dig3 == 0) {
System.out.println(zahl);
} else {
}
}
}
Upvotes: 0
Reputation: 21
public static void methode() {
for (int zahl = 111; zahl <= 999; zahl++) {
if (zahl % 10 == 0 || (zahl % 100)/10 == 0 ) {
continue;
}
else {
int dig1 = zahl / 100;
int dig2 = (zahl % 100) / 10;
int dig3 = zahl % 10;
if (zahl % dig1 == 0 && zahl % dig2 == 0 && zahl % dig3 == 0) {
System.out.println(zahl);
}
else {
continue;
}
}
}}
Try This.
Upvotes: 0
Reputation: 393801
Your condition if (zahl % 10 == 0)
only checks whether the last digit is 0
. You don't perform that check for the second digit (the first digit can never be 0
due to the range of the for loop).
change
if (zahl % dig1 == 0 && zahl % dig2 == 0 && zahl % dig3 == 0)
to
if (dig2 != 0 && dig3 != 0 && zahl % dig1 == 0 && zahl % dig2 == 0 && zahl % dig3 == 0)
Upvotes: 1