首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Java printf 輸出寬度由常量統一控制:字串拼接法

     編輯:程式設計綜合問答

需求場景

希望 System.out.printf 的欄位寬度不寫死,而是由變量 width 控制,例如:

int width = 9;
System.out.printf(" %" + width + "s %" + width + "f\n", str, val);

原理解析

printf 格式字串在編譯期即為常量,無法直接嵌入變量。解決方案是利用字串拼接在運行期動態構建格式字串:"%" + width + "s" 會生成如 "%9s" 的字串,再傳給 printf。

完整示例

public class FormatDemo {
    public static void main(String[] args) {
        int width = 12;
        String name = "Product";
        double price = 1234.56;
        // 動態構建格式字串
        String fmt = "%" + width + "s %" + width + ".2f%n";
        System.out.printf(fmt, name, price);
        // 輸出: "    Product    1234.56"
    }
}

進階:封裝為工具方法

public static void printAligned(int width, Object... args) {
    if (args.length % 2 != 0) throw new IllegalArgumentException("需成對提供 label 和 value");
    StringBuilder fmt = new StringBuilder();
    for (int i = 0; i < args.length; i += 2) {
        fmt.append("%").append(width).append("s %").append(width).append("s%n");
    }
    System.out.printf(fmt.toString(), args);
}

注意事項

  • 拼接頻繁時可用 StringBuilder 提升性能。
  • 若需對齊方向控制,可在 % 後加 -(左對齊)。
  • Java 15+ 可使用 String.format 或 Formatted API 簡化。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved