Подтвердить что ты не робот

Как создать таблицу с помощью ASCII в консоли?

Я хотел бы организовать такую ​​информацию:

Информация организована с помощью ячеек, тогда как System.out.println информация будет очень дезорганизована.

or this

4b9b3361

Ответ 1

Попробуйте использовать System.out.format() или System.out.printf() (printf просто вызывает format, поэтому оба метода дают одинаковые результаты).

Здесь у вас есть простой пример, который попытается выровнять текст слева и заполнить неиспользуемые места пробелами. Выравнивание строки слева может быть достигнуто с помощью %-15s, что означает резерв 15 места для данных строки (s) и начнет записывать его слева (-). Если вы хотите добавить цифры, используйте суффикс d, например %-4d, для максимальных четырехзначных чисел, которые должны быть размещены в левой части столбца.
BTW Я использовал %n вместо \n для представления последовательности разделителей строк, используемой текущей ОС, как для Windows, она будет \r\n.

Дополнительную информацию можно найти в документации класса Formatter.

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

Ответ 2

Попробуйте эту альтернативу: asciitable.

Он предлагает несколько реализаций текстовой таблицы, первоначально использующей символы ASCII и UTF-8 для границ.

Вот пример таблицы:

    ┌──────────────────────────────────────────────────────────────────────────┐
    │ Table Heading                                                            │
    ├──────────────────┬──────────────────┬──────────────────┬─────────────────┤
    │ first row (col1) │ with some        │ and more         │ even more       │
    │                  │ information      │ information      │                 │
    ├──────────────────┼──────────────────┼──────────────────┼─────────────────┤
    │ second row       │ with some        │ and more         │ even more       │
    │ (col1)           │ information      │ information      │                 │
    │                  │ (col2)           │ (col3)           │                 │
    └──────────────────┴──────────────────┴──────────────────┴─────────────────┘

Найти последнюю версию: http://mvnrepository.com/artifact/de.vandermeer/asciitable

См. также: fooobar.com/questions/237377/...

Ответ 3

использовать System.out.printf()

Например,

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

распечатает содержимое строки s, занимая ровно 10 символов. Поэтому, если вам нужна таблица, просто убедитесь, что каждая ячейка в таблице напечатана на той же длине. Также обратите внимание, что printf() не печатает новую строку, поэтому вам придется распечатать ее самостоятельно.

Ответ 5

Мой класс, созданный специально для этого, полностью динамичен: https://github.com/MRebhan/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 chars off (опустить .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]

Ответ 7

Вы можете использовать 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

Ответ 8

TUIAWT позволяет использовать AWT компоненты в консольное окно. Не похоже, что он поддерживает List или Table, но это может дать вам отправную точку.