String [] [] 数组的单元格作为右对齐表打印的最佳方法是什么?例如,输入

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

应该产生输出

  x xxx
yyy   y
 zz  zz

这似乎是应该能够使用 java.util.Formatter 完成的事情,但它似乎不允许非常量字段宽度。最佳答案将使用一些标准方法来填充表格单元格,而不是手动插入空格字符。

有帮助吗?

解决方案

实际上,如果为字段指定宽度,则应该右对齐。
如果你需要一个动态填充,对于最长的字符串是最小的,你必须遍历数组,获得最大宽度,生成具有从这个最大值计算的宽度的格式字符串,并使用它来格式化输出。

其他提示

这是一个答案,为每列使用动态生成的格式字符串:

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<*>quot; + 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]);
    }
  }
}

找到最长字符串的长度..
左边用空格填充所有字符串,直到它们长度为+ 1
System.out.print使用2个嵌套for循环

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top