Search code examples
javatext-alignment

How to print a table of information in Java


I'm trying to print a table in Java and I was wondering what is the best way to do this?

I've tried printing new lines and using \t to make contents line up but it doesn't work. Is there a method which does this or a better way?


Solution

  • You can use System.out.format(...)

    Example:

    final Object[][] table = new String[4][];
    table[0] = new String[] { "foo", "bar", "baz" };
    table[1] = new String[] { "bar2", "foo2", "baz2" };
    table[2] = new String[] { "baz3", "bar3", "foo3" };
    table[3] = new String[] { "foo4", "bar4", "baz4" };
    
    for (final Object[] row : table) {
        System.out.format("%15s%15s%15s%n", row);
    }
    

    Result:

            foo            bar            baz
           bar2           foo2           baz2
           baz3           bar3           foo3
           foo4           bar4           baz4
    

    Or use the following code for left-aligned output:

    System.out.format("%-15s%-15s%-15s%n", row);