You should have implemented a counter of printed characters and in the third nested loop printing spaces on the right side use this value to print spaces until width
is reached:
for (int i = high; i > 0; i--) {
//The left line and the space
System.out.print("|");
int c = 0;
for (int j = high-1; j >= i; j--) {
System.out.print(" ");
c++;
}
//for the stars
for (int k = 1; k <= (i * 2 - 7); k++) {
System.out.print("*");
c++;
}
//The spaces and the right line
for (int j = c; j <= width; j++) {
System.out.print(" ");
}
System.out.print("|");
System.out.println();
}
Also, it is not quite clear why "reverse" loops have been used.
Incrementing loops can do the same:
for (int i = 0; i < high; i++) {
int c = 0;
//The left line and the space
System.out.print("|");
for (int j = 0; j < i; j++) {
System.out.print(" ");
c++;
}
//for the stars
for (int k = 0; k < width - 2 * i + 1; k++) {
System.out.print("*");
c++;
}
//The right line and the space
for (int j = c; j <= width; j++) {
System.out.print(" ");
}
System.out.print("|");
System.out.println();
}
Both codes print the same pyramid:
_ _ _ _ _ _ _ _
|***************|
| ************* |
| *********** |
| ********* |
| ******* |
| ***** |
| *** |
| * |
| |
| |
| |
_ _ _ _ _ _ _ _
String::repeat
-based solution calculating the number of stars beforehand:
for (int i = 0; i < high; i++) {
int stars = Math.max(0, width - 2 * i + 1);
System.out.printf("|%s%s%s|%n", " ".repeat(i), "*".repeat(stars), " ".repeat(width + 1 - i - stars));
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…