You can use System.out.format()
or System.out.printf()
(printf
internally simply invokes format
so both methods give same results).
Below you will find example which will align text to left and fill unused places with spaces. Aligning String to left can be achieved with %-15s
, which means:
%
reserve (placeholder)
15
"places" for characters
s
of String data-type
-
and start printing them from left.
If you want to handle digits use d
suffix like %-4d
for max 4 digit numbers that should be placed at left side of column.
BTW printf
doesn't add automatically line separators after printed data, so if we want to move cursor to next line we need to do it ourselves. We can use
or
, or let Formatter generate OS dependent line separator (like for Windows
) with %n
(note: this "placeholder" doesn't require any data as arguments, Java will provide correct sequence based on OS).
You can find more info about supported syntax at documentation of Formatter
class.
String leftAlignFormat = "| %-15s | %-4d |%n";
System.out.format("+-----------------+------+%n");
System.out.format("| Column name | ID |%n");
System.out.format("+-----------------+------+%n");
for (int i = 0; i < 5; i++) {
System.out.format(leftAlignFormat, "some data" + i, i * i);
}
System.out.format("+-----------------+------+%n");
output
+-----------------+------+
| Column name | ID |
+-----------------+------+
| some data0 | 0 |
| some data1 | 1 |
| some data2 | 4 |
| some data3 | 9 |
| some data4 | 16 |
+-----------------+------+
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…