Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
117 views
in Technique[技术] by (71.8m points)

java - How can I create table using ASCII in a console?

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

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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   |
+-----------------+------+

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...