for (int j = 1; j <= 5 - i; j++) {
System.out.print(""); // 這裡應該是空格 " "
}
System.out.print("") 輸出**空字符串**,不佔寬度,導致每行前導空白缺失,三角形左邊緣靠左,不再居中。
System.out.print(" "); // 雙引號內打一個空格
public class IsoscelesTriangle {
public static void main(String[] args) {
int rows = 5;
for (int i = 1; i <= rows; i++) {
// 打印前導空格
for (int j = 1; j <= rows - i; j++) {
System.out.print(" ");
}
// 打印星號
for (int k = 1; k <= 2 * i - 1; k++) {
System.out.print("*");
}
System.out.println(); // 換行
}
}
}
*
***
*****
*******
*********
* 或空格。String.repeat(n) (Java 11+) 簡化:System.out.print(" ".repeat(rows-i) + "*".repeat(2*i-1));一個空格的缺失,改變了整個圖形結構。**字符串字面量 "" 與 " " 天壤之別**,調試輸出格式時,可用 System.out.print("[" + str + "]") 可視化邊界。