Warm tip: This article is reproduced from stackoverflow.com, please click
java console

How can I create table using ASCII in a console?

发布于 2020-03-30 21:14:43

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.

or this

Questioner
Mike Brian Olivera
Viewed
26
Pshemo 2018-08-24 20:29

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 wan want to move cursor to next line we need to do it ourselves. We can use \r or \n, or to let Formatter generate OS dependent line separator (like for Windows \r\n) we can use %n placeholder (note: it doesn't require any data as arguments, Java will provide correct sequence based on OS).

You can find more info about syntax supported by Formatter at documentation of that 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   |
+-----------------+------+