问题描述
我想整理下列资讯:
信息是用单元格组织的,而 System.out.println
The information is organized with cells, whereas with System.out.println
the information would be very disorganized.
推荐答案
尝试使用 System.out.format()
或系统.out.printf()
( printf
只需调用格式
)。
Try using System.out.format()
or System.out.printf()
(printf
simply invokes format
so both methods gives same results).
这里有一个简单的示例,它将尝试将文本向左对齐并用空格填充未使用的位置。可以使用%-15s
实现左对齐字符串,这意味着 15
字符串的位置( s
)数据并从左开始写( -
)。如果要添加数字,应使用 d
后缀,如% - 4d
BTW我使用%n
而不是 \\\
来表示行当前操作系统使用的分隔符序列,对于Windows,它将是
\r\\\
。
Here you have simple example that will try to align text to left and fill unused places with spaces. Aligning String to left can be achieved with %-15s
, which means reserve 15
places for string (s
) data and start writing it from left (-
). If you want to add digits use d
suffix like %-4d
for max 4 digit numbers that should be placed at left side of column.
BTW I used %n
instead of \n
to represents line separator sequence used by current OS like for Windows it will be \r\n
.
您可以在。
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");
输出
+-----------------+------+
| Column name | ID |
+-----------------+------+
| some data0 | 0 |
| some data1 | 1 |
| some data2 | 4 |
| some data3 | 9 |
| some data4 | 16 |
+-----------------+------+
这篇关于如何在控制台中使用ASCII创建表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!