Aligned CLI Table With Repeat And Printf

Render readable report tables from a plain CLI with String.repeat rules and printf column widths, staying inside the standard library.

JavaCli Tooling

Code

snippet
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);
    }
}

How it works

One way to read it: the classes LatencyTable and Row and the functions center and main, doing all the work.

Iteration happens inside for (Row row : rows) — everything outside it runs once.

Watch out for

  • Every name resolves to a language built-in — there is nothing to download.

Using it

Signature: static String center(String text, int width)

The demo flow inside main is center — run the file to see it end to end.

Key statements

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

Interactive Tools for This Topic

FAQ

How do you run Aligned CLI Table With Repeat And Printf?
Run the file on its own; every call resolves against the standard surface it already imports.