You should be able to simplify this considerably.
I'd suggest using nested loops and putting a single if
inside of these loops to determine which type of character to print, as opposed to a series of flat loops that handle each "run" to build a row in multiple steps as you're currently doing.
The "X" star locations are determined by the condition j == i || j == n - i - 1
where i
is the current row index and j
is the current column index.
For the first and last stars in each row, you can use the condition j == 0 || j == n - 1
.
Combining the twoabove four conditions gives a clear way to determine when to print a star or not for each cell.
For example:
public class Main {
public static void printButterfly(int n) {
n *= 2;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (j == 0 || j == i || j == n - i - 1 || j == n - 1) {
System.out.print("*");
}
else {
System.out.print(" ");
}
}
System.out.println();
}
}
public static void main(String[] args) {
printButterfly(5);
}
}