行號 i (1-based),每行星號數與空格數由 i 決定。關鍵公式:
i 行 → 2*i-1 個星號i 行 → 2*i-3 個星號 (從倒數第 2 行開始)4-i 空格 + 2*i-1 星號5-i 空格 + 2*i-3 星號public class Triangle {
public static void main(String[] args) {
int h = 4;
// 正三角
for (int i = 1; i <= h; i++) {
printChars(' ', h - i); // 左側空格 (可選,居中)
printChars('*', 2 * i - 1); // 星號
System.out.println();
}
// 倒三角 (不含頂點重複)
for (int i = h - 1; i >= 1; i--) {
printChars(' ', h - i);
printChars('*', 2 * i - 1);
System.out.println();
}
}
static void printChars(char c, int n) {
for (int i = 0; i < n; i++) System.out.print(c);
}
}
輸出:
*
***
*****
*******
*****
***
*
public class Diamond {
public static void main(String[] args) {
int h = 4;
// 上半部 (含中線)
for (int i = 1; i <= h; i++) {
printChars(' ', h - i); // 左側空格
printChars('*', 2 * i - 1); // 星號
System.out.println();
}
// 下半部 (不含中線)
for (int i = h - 1; i >= 1; i--) {
printChars(' ', h - i);
printChars('*', 2 * i - 1);
System.out.println();
}
}
static void printChars(char c, int n) {
for (int i = 0; i < n; i++) System.out.print(c);
}
}
輸出:
*
***
*****
*******
*****
***
*
public class DiamondGeneric {
public static void printDiamond(int h) {
// 上半部
for (int i = 1; i <= h; i++)
System.out.println(" ".repeat(h - i) + "*".repeat(2 * i - 1));
// 下半部
for (int i = h - 1; i >= 1; i--)
System.out.println(" ".repeat(h - i) + "*".repeat(2 * i - 1));
}
public static void main(String[] args) {
printDiamond(5);
// Java 11+ String.repeat() 簡化打印
}
}
| 模式 | 第 i 行星號數 | 第 i 行空格數 |
|---|---|---|
| 左對齊直角三角 | i | 0 |
| 右對齊直角三角 | i | h-i |
| 空心三角形 | 首尾星號,中間空格 | h-i |
| 帕斯卡三角形 | 組合數 C(i-1, j-1) | 視寬度 |
| 數字金字塔 | 遞增/遞減數字 | h-i |