Java: printing a 2D String array as a right-aligned table

What is the best way to print array cells String[][]as a right-aligned table? For example, input

{ { "x", "xxx" }, { "yyy", "y" }, { "zz", "zz" } }

should output

  x xxx
yyy   y
 zz  zz

This is similar to what can be done with java.util.Formatter, but does not seem to allow the use of a variable field width. A better answer would be to use the standard method to fill in the cells of a table rather than manually insert spaces.

+2
source share
3 answers

, , .
, , , , , , .

+4

, :

public static void printTable(String[][] table) {
  // Find out what the maximum number of columns is in any row
  int maxColumns = 0;
  for (int i = 0; i < table.length; i++) {
    maxColumns = Math.max(table[i].length, maxColumns);
  }

  // Find the maximum length of a string in each column
  int[] lengths = new int[maxColumns];
  for (int i = 0; i < table.length; i++) {
    for (int j = 0; j < table[i].length; j++) {
      lengths[j] = Math.max(table[i][j].length(), lengths[j]);
    }
  }

  // Generate a format string for each column
  String[] formats = new String[lengths.length];
  for (int i = 0; i < lengths.length; i++) {
   formats[i] = "%1$" + lengths[i] + "s" 
       + (i + 1 == lengths.length ? "\n" : " ");
 }

  // Print 'em out
  for (int i = 0; i < table.length; i++) {
    for (int j = 0; j < table[i].length; j++) {
      System.out.printf(formats[j], table[i][j]);
    }
  }
}
+4

.
left pad , + 1
System.out.print, 2

+1

All Articles