Moderation Note: This answer was being typed at the same time as the asker changed his code, to avoid this bug. Here's the code, as it was, when this answer was typed:
Program that prints out repetitives of 3,5 and both of them
public static void main(String args[]) {
for(int i = 1; i < 101; i++)
{
if(i%3 == 0)
{
System.out.println("repetitive of 3");
}
else if(i%5 == 0)
{
System.out.println("repetitive of 5");
}
else if(i%5 == 0 && i%3 == 0)
{
System.out.println("repetitive of 3 and 5");
}
else{
System.out.println(i);
}
}
}
}
First of please format your code properly as it helps to read it. I've formatted the code as it is suggested for java:
public static void main(String args[]) {
for (int i = 1; i < 101; i++) {
if (i%3 == 0) {
System.out.println("repetitive of 3");
} else if (i%5 == 0) {
System.out.println("repetitive of 5");
} else if (i%5 == 0 && i%3 == 0) {
System.out.println("repetitive of 3 and 5");
} else {
System.out.println(i);
}
}
}
Now for the review:
The third if
will never be reached as the first if
already matches.
So to get the result wanted you have to change the first and third if branch:
public static void main(String args[]) {
for (int i = 1; i < 101; i++) {
if (i%5 == 0 && i%3 == 0) {
System.out.println("repetitive of 3 and 5");
} else if (i%5 == 0) {
System.out.println("repetitive of 5");
} else if (i%3 == 0) {
System.out.println("repetitive of 3");
} else {
System.out.println(i);
}
}
}
Using the method main()
for small tests is fine but it is better to create objects and use them from the beginning.
Else the program look good so far.