I'd go with String#format()
/ System.out.printf()
:
System.out.printf("%21s %9s %9s %9s\n",
df.format(/* ... */),
df.format(/* ... */),
df.format(/* ... */),
df.format(/* ... */));
%9s
means: string with a length of 9 characters. If the string is shorter than 9 characters, spaces are appended at the front, so the text is right-aligned. If you want the text to be left-aligned, you can use %-9s
.
System.out.printf("%11s | %9s | %9s | %9s\n", "Orig. Temp.", "Temp in C", "Temp in F", "Temp in K");
System.out.printf("%11s | %9s | %9s | %9s\n", "213.0", "99.6", "213.0", "372.7");
System.out.printf("%11s | %9s | %9s | %9s\n", "321.0", "321.0", "609.8", "594.1");
produces:
Orig. Temp. | Temp in C | Temp in F | Temp in K
213.0 | 99.6 | 213.0 | 372.7
321.0 | 321.0 | 609.8 | 594.1
(or left-aligned: %-9s
)
Orig. Temp. | Temp in C | Temp in F | Temp in K
213.0 | 99.6 | 213.0 | 372.7
321.0 | 321.0 | 609.8 | 594.1
(or centered)
private static void print() {
// header
System.out.printf("%11s | %9s | %9s | %9s\n", "Orig. Temp.", "Temp in C", "Temp in F", "Temp in K");
// values
System.out.printf("%-11s | %-9s | %-9s | %-9s\n", center("213.0", 11), center("99.6", 9), center( "213.0", 9), center("372.7", 9));
System.out.printf("%-11s | %-9s | %-9s | %-9s\n", center("321.0", 11), center("321.0", 9), center("609.8", 9), center("594.1", 9));
}
private static String center(String str, int size) {
if (str.length() >= size) {
return str;
}
final StringBuilder builder = new StringBuilder();
for (int i = 0; i < (size - str.length()) / 2; i++) {
builder.append(' ');
}
builder.append(str);
for(int i = 0; i < (builder.length() - size); i++) {
builder.append(' ');
}
return builder.toString();
}
produces:
Orig. Temp. | Temp in C | Temp in F | Temp in K
213.0 | 99.6 | 213.0 | 372.7
321.0 | 321.0 | 609.8 | 594.1