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);
}
}
}
}
Improve with
elseAs all the if are exclusives (only one condition at each iteration can be true), you can put an
elseeverywhere. As you domodulo%6you can even put a simpleelsefor the final oneImprove with deduplicated blocks
Note that you can duplicated cases,
1,5and2,4, so you can doImprove with switch and string concatenation
You can also use a
switch(here the new enhanced switch with blocks that don't requirebreakstatements), and concatenate the string to get one print callImprove with easier code
You can also just store the prefixes and suffixes in arrays and access them