希望 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 提升性能。% 後加 -(左對齊)。String.format 或 Formatted API 簡化。