如何在控制台中使用 ASCII 创建表? [英] How can I create table using ASCII in a console?

查看:26
本文介绍了如何在控制台中使用 ASCII 创建表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想像这样组织信息:

信息是用单元格组织的,而如果使用System.out.println,信息会非常混乱.

The information is organized with cells, whereas with System.out.println the information would be very disorganized.

推荐答案

您可以使用 System.out.format()System.out.printf() (printf 在内部简单地调用 format,因此两种方法都给出相同的结果).

You can use System.out.format() or System.out.printf() (printf internally simply invokes format so both methods give same results).

您将在下面找到示例,该示例将文本左对齐并用空格填充未使用的位置.使用%-15s可以实现String左对齐,即:

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:

  • % 保留(占位符)
  • 15 地方"对于字符
  • s 的 String 数据类型
  • - 并从左侧开始打印它们.
  • % reserve (placeholder)
  • 15 "places" for characters
  • s of String data-type
  • - and start printing them from left.

如果您想处理数字,请使用 d 后缀,如 %-4d 表示应放置在左侧的最多 4 位数字列.

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 不会在打印数据后自动添加行分隔符,所以如果我们想将光标移动到下一行,我们需要自己做.我们可以使用 ,或者让 Formatter 使用 生成操作系统相关的行分隔符(如 Windows )>%n(注意:这个占位符"不需要任何数据作为参数,Java 将根据操作系统提供正确的序列.

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).

您可以在 Formatter 类的文档.

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");

输出

+-----------------+------+
| Column name     | ID   |
+-----------------+------+
| some data0      | 0    |
| some data1      | 1    |
| some data2      | 4    |
| some data3      | 9    |
| some data4      | 16   |
+-----------------+------+

这篇关于如何在控制台中使用 ASCII 创建表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆