I would like to organize information like this:
The information is organized with cells, whereas with System.out.println
the information would be very disorganized.
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 characterss
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 \r
or \n
, or let Formatter generate OS dependent line separator (like for Windows \r\n
) 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 | +-----------------+------+
Try this alternative: asciitable.
It offers several implementations of a text table, originally using ASCII and UTF-8 characters for borders.
Here is a sample table:
┌──────────────────────────────────────────────────────────────────────────┐ │ Table Heading │ ├──────────────────┬──────────────────┬──────────────────┬─────────────────┤ │ first row (col1) │ with some │ and more │ even more │ │ │ information │ information │ │ ├──────────────────┼──────────────────┼──────────────────┼─────────────────┤ │ second row │ with some │ and more │ even more │ │ (col1) │ information │ information │ │ │ │ (col2) │ (col3) │ │ └──────────────────┴──────────────────┴──────────────────┴─────────────────┘
Find the latest version: http://mvnrepository.com/artifact/de.vandermeer/asciitable
See also: https://stackoverflow.com/a/39806611/363573
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With