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.
Code
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
Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Indentation ConverterConvert leading indentation between tabs and spaces at a chosen width, leaving inner content untouched.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.