列印金字塔是經典入門題目,通常使用雙層巢狀迴圈。但巢狀迴圈易產生索引變數混淆、邏輯難以維護。本例展示如何透過方法抽離,將每層邏輯封裝為獨立方法,實現「單層迴圈」原則。
public class Pyramid {
public static void main(String[] args) {
printPyramid(21, '*'); // 底寬 21 (奇數)
}
// 主迴圈:僅控制層數
private static void printPyramid(int bottom_width, char ch) {
if (bottom_width < 1 || bottom_width % 2 == 0) throw new IllegalArgumentException();
int height = bottom_width / 2 + 1;
for (int i = 0; i < height; i++) {
int width = i * 2 + 1;
System.out.println(getLevel(bottom_width, width, ch));
}
}
// 產生單層字串:前置空格 + 字元
private static String getLevel(int bottom_width, int width, char ch) {
int space_width = (bottom_width - width) / 2;
return expand(' ', space_width) + expand(ch, width);
}
// 產生指定長度字元字串
private static String expand(char c, int width) {
char[] chars = new char[width];
Arrays.fill(chars, c);
return new String(chars);
}
}
getLevel、expand 可獨立單元測試。i/j 混淆風險。Arrays.fill() 內部仍以迴圈實作,但屬於 JDK 內部實作細節,不影響業務邏輯可讀性。