【问题标题】:How can I create table using ASCII in a console?如何在控制台中使用 ASCII 创建表?
【发布时间】:2013-02-19 08:29:30
【问题描述】:

我想整理这样的信息:

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

【问题讨论】:

  • +1。不是一个坏问题。如果有人对此有很好的图书馆,请推荐。否则,请查看 System.out.format
  • 您可以查看this 的示例
  • 您最好的选择主要是使用System.out.printf(...) 和等效的System.out.format(...)
  • 不是 ASCII 表,但这里有类似的问题 .. stackoverflow.com/questions/5551186/…
  • mysnortlmao

标签: java console


【解决方案1】:

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

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

  • %reserve(占位符)
  • 15 字符的“地点”
  • 字符串数据类型的s
  • - 并从左侧开始打印。

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

BTW printf 不会在打印数据后自动添加行分隔符,所以如果我们想将光标移动到下一行,我们需要自己做。我们可以使用\r\n,或者让Formatter 使用%n 生成依赖于操作系统的行分隔符(如Windows \r\n)(注意:这个“占位符”不需要任何数据作为参数,Java 会根据操作系统提供正确的序列)。

您可以在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   |
+-----------------+------+

【讨论】:

  • ¡¡完美答案!!太感谢了!我可以做到我想要的 =)
  • 对于固定需求,这个解决方案是完美的。对于更多现实生活中的用例,库更合适。看到这个答案:stackoverflow.com/a/35961774/363573.
【解决方案2】:

试试这个替代方案:asciitable

它提供了文本表的多种实现,最初使用 ASCII 和 UTF-8 字符作为边框。

这是一个示例表:

 ┌────────────────────────────────────────────── ────────────────────────────┐
    │ 表格标题 │
    ├──────────────────┬──────────────────┬─────────── ────────┬──────────────────┤
    │第一行(col1)│有一些│还有更多│甚至更多│
    │ │ 信息 │ 信息 │ │
    ├──────────────────┼──────────────────┼──────────── ────────┼──────────────────┤
    │第二排│有一些│还有更多│甚至更多│
    │ (col1) │ 信息 │ 信息 │ │
    │ │ (col2) │ (col3) │ │
    └──────────────────┴──────────────────┴──────────── ────────┴──────────────────┘

查找最新版本: http://mvnrepository.com/artifact/de.vandermeer/asciitable

另请参阅: https://stackoverflow.com/a/39806611/363573

【讨论】:

  • 另外,他们有一些漂亮的桌子设计there
【解决方案3】:

我专门为此创建的课程是完全动态的: https://github.com/2xsaiko/crogamp/blob/master/src/com/github/mrebhan/crogamp/cli/TableList.java

你可以这样使用它:

TableList tl = new TableList(3, "ID", "String 1", "String 2").sortBy(0).withUnicode(true);
// from a list
yourListOrWhatever.forEach(element -> tl.addRow(element.getID(), element.getS1(), element.getS2()));
// or manually
tl.addRow("Hi", "I am", "Bob");

tl.print();

使用 unicode 字符看起来像这样(注意:在控制台中看起来会更好,因为所有字符都一样宽):

┌─────────┬─────────────────────────────────────────────────────────────────────────┬────────────────────────────┐
│ Command │ Description                                                             │ Syntax                     │
┢━━━━━━━━━╈━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╈━━━━━━━━━━━━━━━━━━━━━━━━━━━━┪
┃ bye     ┃ Quits the application.                                                  ┃                            ┃
┃ ga      ┃ Adds the specified game.                                                ┃ <id> <description> <path>  ┃
┃ gl      ┃ Lists all currently added games                                         ┃ [pattern]                  ┃
┃ gr      ┃ Rebuilds the files of the currently active game.                        ┃                            ┃
┃ gs      ┃ Selects the specified game.                                             ┃ <id>                       ┃
┃ help    ┃ Lists all available commands.                                           ┃ [pattern]                  ┃
┃ license ┃ Displays licensing info.                                                ┃                            ┃
┃ ma      ┃ Adds a mod to the currently active game.                                ┃ <id> <file>                ┃
┃ md      ┃ Deletes the specified mod and removes all associated files.             ┃ <id>                       ┃
┃ me      ┃ Toggles if the selected mod is active.                                  ┃ <id>                       ┃
┃ ml      ┃ Lists all mods for the currently active game.                           ┃ [pattern]                  ┃
┃ mm      ┃ Moves the specified mod to the specified position in the priority list. ┃ <id> <position>            ┃
┃ top kek ┃ Test command. Do not use, may cause death and/or destruction            ┃                            ┃
┃ ucode   ┃ Toggles advanced unicode. (Enhanced characters)                         ┃ [on|true|yes|off|false|no] ┃
┗━━━━━━━━━┻━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┻━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛

并且关闭 unicode 字符(省略 .withUnicode(true)):

Command | Description                                                             | Syntax                    
--------+-------------------------------------------------------------------------+---------------------------
bye     | Quits the application.                                                  |                           
ga      | Adds the specified game.                                                | <id> <description> <path> 
gl      | Lists all currently added games                                         | [pattern]                 
gr      | Rebuilds the files of the currently active game.                        |                           
gs      | Selects the specified game.                                             | <id>                      
help    | Lists all available commands.                                           | [pattern]                 
license | Displays licensing info.                                                |                           
ma      | Adds a mod to the currently active game.                                | <id> <file>               
md      | Deletes the specified mod and removes all associated files.             | <id>                      
me      | Toggles if the selected mod is active.                                  | <id>                      
ml      | Lists all mods for the currently active game.                           | [pattern]                 
mm      | Moves the specified mod to the specified position in the priority list. | <id> <position>           
top kek | Test command. Do not use, may cause death and/or destruction            |                           
ucode   | Toggles advanced unicode. (Enhanced characters)                         | [on|true|yes|off|false|no]

【讨论】:

    【解决方案4】:

    使用System.out.printf()

    例如,

    String s = //Any string
    System.out.printf(%10s, s);
    

    将打印出 String 的内容,正好占用 10 个字符。因此,如果您想要一个表格,只需确保表格中的每个单元格都打印为相同的长度。另请注意,printf() 不会打印新行,因此您必须自己打印。

    【讨论】:

      【解决方案5】:

      您可以使用java-ascii-table。另见the author's site

      【讨论】:

      【解决方案6】:

      我是这样做的

      示例:打印一个表格,其中 1

      public class PrimeEquation
      {
          public static void main(String[] args)
          {
              String header = "";
              header += formatDiv("a-----b-------------b----------c\n");
              header += formatRow("|  x  | x² - x + 41 | Is Prime |\n");
              header += formatDiv("d-----e-------------e----------f\n");
              System.out.print(header);
      
              for (int x = 2; x <= 41; x++)
              {
                  int y = primeEquation(x);
                  String str1 = String.format("| %3d | %11d | %8b |", x, y, MyPrimes.isPrime(y));
                  System.out.println(formatRow(str1));
              }
      
              System.out.println(formatDiv("g-----h-------------h----------i"));
          }
      
          public static int primeEquation(int x)
          {
              return (x*x) - x + 41;
          }
      
          public static String formatRow(String str)
          {
              return str.replace('|', '\u2502');
          }
      
          public static String formatDiv(String str)
          {
              return str.replace('a', '\u250c')
                      .replace('b', '\u252c')
                      .replace('c', '\u2510')
                      .replace('d', '\u251c')
                      .replace('e', '\u253c')
                      .replace('f', '\u2524')
                      .replace('g', '\u2514')
                      .replace('h', '\u2534')
                      .replace('i', '\u2518')
                      .replace('-', '\u2500');
          }
      }
      

      输出:

      【讨论】:

        【解决方案7】:

        这也很有效http://sourceforge.net/projects/texttablefmt/。 Apache 也获得许可。

        【讨论】:

        【解决方案8】:

        你可以用正确的方法使用 string.format() 我猜代码可能看起来像这样

        StringBuilder sb=new StringBuilder();
        
        for(int i = 1; i <= numberOfColumns; i++)
         {
               sb.append(String.format(%-10s,rsMetaData.getColumnLabel(i);
         }
        

        至于图书馆,我认为没有任何东西可以完成这项工作,但我可能弄错了!实际上会对此进行研究

        也看看这个http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html#syntax

        【讨论】:

          【解决方案9】:

          TUIAWT 允许您在控制台窗口中使用AWT 组件。虽然它看起来不支持ListTable,但它可能会给你一个起点。

          【讨论】:

          • 撰写本文时,TUIAWT 的最后一次更新似乎是在 2015 年 3 月。
          【解决方案10】:

          您可以使用 Spring Shell 实用程序类 org.springframework.shell.table.TableModel:

                TableModel model = new BeanListTableModel<>(portConfigurations, headers);
              TableBuilder tableBuilder = new TableBuilder(model);
              tableBuilder.addFullBorder(BorderStyle.oldschool);
              //TableUtils.applyStyle(tableBuilder);
              return tableBuilder.build().render(100);
          

          【讨论】:

            【解决方案11】:

            我尝试使用这些功能解决此问题

            • 列的动态宽度
            • 如果宽度超过最大值,则将其换行到下一行。

            这是simple pure java solution,您可以根据需要使用。

            输出将如下所示。

            +----+------------+--------------------------------+-----+--------------------------------+
            | id | First Name | Last Name                      | Age | Profile                        |
            +----+------------+--------------------------------+-----+--------------------------------+
            | 1  | John       | Johnson                        | 45  | My name is John Johnson. My id |
            |    |            |                                |     |  is 1. My age is 45.           |
            |    |            |                                |     |                                |
            | 2  | Tom        |                                | 35  | My name is Tom. My id is 2. My |
            |    |            |                                |     |  age is 35.                    |
            |    |            |                                |     |                                |
            | 3  | Rose       | Johnson Johnson Johnson Johnso | 22  | My name is Rose Johnson. My id |
            |    |            | n Johnson Johnson Johnson John |     |  is 3. My age is 22.           |
            |    |            | son Johnson Johnson            |     |                                |
            |    |            |                                |     |                                |
            | 4  | Jimmy      | Kimmel                         |     | My name is Jimmy Kimmel. My id |
            |    |            |                                |     |  is 4. My age is not specified |
            |    |            |                                |     | . I am the host of the late ni |
            |    |            |                                |     | ght show. I am not fan of Matt |
            |    |            |                                |     |  Damon.                        |
            |    |            |                                |     |                                |
            +----+------------+--------------------------------+-----+--------------------------------+
            

            【讨论】:

              【解决方案12】:

              以防万一有人需要这种类型的表格:

              +----+----+----+----+----+
              |  1 |  2 |  3 |  4 |  5 |
              +----+----+----+----+----+
              |  6 |  7 |  8 |  9 | 10 |
              +----+----+----+----+----+
              | 11 | 12 | 13 | 14 | 15 |
              +----+----+----+----+----+
              | 16 | 17 | 18 | 19 | 20 |
              +----+----+----+----+----+
              | 21 | 22 | 23 | 24 | 25 |
              +----+----+----+----+----+
              

              这是我的解决方案:

              public class TableShape {
              
                  public static void main(String[] args) {
                      int width_and_height=5;
                      int count=1; 
              
                      for(int i=0;i<width_and_height ; i++) {
                          System.out.println("+----+----+----+----+----+");
              
                          for(int j=0;j<width_and_height;j++) {
                              System.out.format("| %2d ", count++);
              
                              if(j==width_and_height-1) { // closing | for last column
                                  System.out.print("|");
                              }
                          }
                          System.out.println();
                          if(i==width_and_height-1) { // closing line for last row
                              System.out.print("+----+----+----+----+----+");
                          }
                      }
              
                  }
              }
              

              【讨论】:

                猜你喜欢
                • 2011-02-13
                • 2011-02-13
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多