首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

重構金字塔列印程式:拒絕巢狀迴圈,採用方法抽離提升可讀性

     編輯:Java 相關知識

列印金字塔是經典入門題目,通常使用雙層巢狀迴圈。但巢狀迴圈易產生索引變數混淆、邏輯難以維護。本例展示如何透過方法抽離,將每層邏輯封裝為獨立方法,實現「單層迴圈」原則。

重構後架構

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 內部實作細節,不影響業務邏輯可讀性。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved