← 中文资源

简体中文版本

repeat 与 printf 对齐 CLI 表格

用 String.repeat 画分隔线与居中标题、printf 的宽度标志对齐每一列,纯标准库就能渲染可读的 CLI 报表表格,不引入任何依赖。

阅读英文原文

实现说明

活动部件是类 LatencyTable、Row和函数 center、main。 文件的主干是一个循环——for (Row row : rows)。

使用要点

  • 执行文件,main 会按顺序走完 center。

常见问题

「repeat 与 printf 对齐 CLI 表格」这个示例怎么运行?

把它当完整程序编译/解释运行即可——不需要先安装任何东西。

签名一览:static String center(String text, int width)

核心语句

return " ".repeat(left) + text + " ".repeat(pad - left);

代码示例

import java.util.List;

public class LatencyTable {

    record Row(String service, String region, int p99Millis) {}

    // Center by padding both sides: the remainder goes to the right, and text wider than the width passes through unchanged
    static String center(String text, int width) {
        int pad = Math.max(0, width - text.length());
        int left = pad / 2;
        return " ".repeat(left) + text + " ".repeat(pad - left);
    }

    public static void main(String[] args) {
        List<Row> rows = List.of(
                new Row("orders", "eu-west-1", 42),
                new Row("billing", "us-east-1", 137),
                new Row("auth", "ap-southeast-2", 9));

        System.out.println(center("deployment latency", 38));
        String rule = "-".repeat(38);
        System.out.println(rule);
        // Aligned columns for the CLI report: printf width flags control left/right alignment per column
        System.out.printf("%-10s %-15s %10s%n", "service", "region", "p99 ms");
        for (Row row : rows) {
            System.out.printf("%-10s %-15s %10d%n",
                    row.service(), row.region(), row.p99Millis());
        }
        System.out.println(rule);
    }
}