where should I insert "else" to reduce "if"
public class Main2 {
public static void main(String[] args) {
for(int i=1;i<=12;i++) {
if(i%6 ==1) {
System.out.print(" ");
System.out.print(i);
System.out.println("-");
}
if(i%6 ==2) {
System.out.print("+");
System.out.println(i);
}
if(i%6 ==3) {
System.out.print(" ");
System.out.print(i);
System.out.println("#");
}
if(i%6 ==4) {
System.out.print("+");
System.out.println(i);
}
if(i%6 ==5) {
System.out.print(" ");
System.out.print(i);
System.out.println("-");
}
if(i%6 ==0) {
System.out.print("#");
System.out.println(i);
}
}
}
}
else
As all the if are exclusives (only one condition at each iteration can be true), you can put an else
everywhere. As you do modulo%6
you can even put a simple else
for the final one
if (i % 6 == 1) {
} else if (i % 6 == 2) {
} else if (i % 6 == 3) {
} else if (i % 6 == 4) {
} else if (i % 6 == 5) {
} else {
}
Note that you can duplicated cases, 1,5
and 2,4
, so you can do
if (i % 6 == 1 || i % 6 == 5) {
} else if (i % 6 == 2 || i % 6 == 4) {
} else if (i % 6 == 3) {
} else {
}
You can also use a switch
(here the new enhanced switch with blocks that don't require break
statements), and concatenate the string to get one print call
switch (i % 6) {
case 1, 5 -> System.out.println(" " + i + "-");
case 2, 4 -> System.out.println("+" + i);
case 3 -> System.out.println(" " + i + "#");
default -> System.out.println("#" + i);
}
You can also just store the prefixes and suffixes in arrays and access them
String[] prefixes = {" ", "+", " ", "+", " ", "#"};
String[] suffixes = {"-", "", "#", "", "-", ""};
for (int i = 1; i <= 12; i++) {
System.out.println(prefixes[(i - 1) % 6] + i + suffixes[(i - 1) % 6]);
}