以 5 行正金字塔為例,第 i 行(1-based):
| 行數 | 空格 | 星號 |
|---|---|---|
| 1 | 4 | 1 |
| 2 | 3 | 3 |
| 3 | 2 | 5 |
| 4 | 1 | 7 |
| 5 | 0 | 9 |
public static void uprightPyramid(int rows) {
for (int i = 1; i <= rows; i++) {
for (int s = 1; s <= rows - i; s++) System.out.print(" ");
for (int k = 1; k <= 2*i - 1; k++) System.out.print("★");
System.out.println();
}
}
public static void fallPyramid(int rows) {
for (int i = rows; i >= 1; i--) {
for (int s = 0; s < rows - i; s++) System.out.print(" ");
for (int k = 0; k < 2*i - 1; k++) System.out.print("★");
System.out.println();
}
}
public static void diamond(int rows) {
uprightPyramid(rows);
fallPyramid(rows - 1); // 避免中間行重複
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("選擇:0-正金字塔 1-倒金字塔 2-菱形 3-退出");
String input = sc.nextLine();
if (!input.matches("\\d+")) { System.out.println("請輸入數字!"); continue; }
int choice = Integer.parseInt(input);
if (choice == 3) break;
System.out.print("請輸入行數:");
int rows = Integer.parseInt(sc.nextLine());
switch (choice) {
case 0: uprightPyramid(rows); break;
case 1: fallPyramid(rows); break;
case 2: diamond(rows); break;
default: System.out.println("選項錯誤!");
}
}
}
