How can I create table using ASCII in a console?

JavaConsole

Java Problem Overview


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

Java Solutions


Solution 1 - Java

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 \r or \n, or let Formatter generate OS dependent line separator (like for Windows \r\n) 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   |
+-----------------+------+

Solution 2 - Java

Try this alternative: asciitable.

It offers several implementations of a text table, originally using ASCII and UTF-8 characters for borders.

Here is a sample table:

	 ┌──────────────────────────────────────────────────────────────────────────┐
│ 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)           │                 │
└──────────────────┴──────────────────┴──────────────────┴─────────────────┘

Find the latest version: http://mvnrepository.com/artifact/de.vandermeer/asciitable

See also: https://stackoverflow.com/a/39806611/363573

Solution 3 - Java

My class I created specifically for doing this is completely dynamic: https://github.com/2xsaiko/crogamp/blob/master/src/com/github/mrebhan/crogamp/cli/TableList.java

You can use it like this:

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

It will look like this with unicode chars (note: will look better in console since all chars are equally wide):

┌─────────┬─────────────────────────────────────────────────────────────────────────┬────────────────────────────┐
│ 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] ┃
┗━━━━━━━━━┻━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┻━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛

And with unicode chars off (omit the .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]

Solution 4 - Java

use System.out.printf()

For example,

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

will print out the contents of String s, taking up exactly 10 characters. So if you want a table, just make sure each cell in the table is printed out to the same length. Also notice that printf() doesn't print a new line, so you'll have to print it yourself.

Solution 5 - Java

You could use java-ascii-table. See also the author's site.

Solution 6 - Java

I do it this way

Example: Print a table with the values of x² - x + 41 for 1 < x < 42

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');
    }
}

Output:

Table

Solution 7 - Java

This also works pretty well http://sourceforge.net/projects/texttablefmt/. Apache licensed too.

Solution 8 - Java

You can use string.format() with correct method Code could look something like this i guess

StringBuilder sb=new StringBuilder();

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

As of library i dont think there is any that would do the job, however i might be mistaken! will actually do research on it

Also have a look at this http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html#syntax

Solution 9 - Java

TUIAWT lets you use AWT components in a console window. It doesn't look like it supports List or Table, though, but it may give you a starting point.

Solution 10 - Java

You can use Spring Shell utility class 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);

Solution 11 - Java

I attempted a solution for this with these features

  • Dynamic width of columns
  • If width beyond max, then wrap it to next line.

Here is the simple pure java solution which you can use as per your need.

Output will look something like this.

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

Solution 12 - Java

Just in case somebody needs this type of table:

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

Here is my solution:

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("+----+----+----+----+----+");
			}
		}

	}
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMike Brian OliveraView Question on Stackoverflow
Solution 1 - JavaPshemoView Answer on Stackoverflow
Solution 2 - JavaStephanView Answer on Stackoverflow
Solution 3 - Java2xsaikoView Answer on Stackoverflow
Solution 4 - JavajedyobidanView Answer on Stackoverflow
Solution 5 - JavakfoxonView Answer on Stackoverflow
Solution 6 - JavaDavid CelyView Answer on Stackoverflow
Solution 7 - JavaAshwin JayaprakashView Answer on Stackoverflow
Solution 8 - JavaMaciej CyganView Answer on Stackoverflow
Solution 9 - Javahd1View Answer on Stackoverflow
Solution 10 - Javauser2600734View Answer on Stackoverflow
Solution 11 - JavaRavi KView Answer on Stackoverflow
Solution 12 - JavaRebaz NajeebView Answer on Stackoverflow