【问题标题】:Using printf to align numbers and headings in a table使用 printf 对齐表格中的数字和标题
【发布时间】:2014-04-09 03:29:45
【问题描述】:

我从来没有正确理解 printf 的工作原理,并且确实可以使用一些格式化帮助。我希望我的打印输出如下所示:

Student     Correct      Incorrect
   1           3             7
   2           4             6
   3           8             2

如此等等。我只是想不出格式化我的 printf 语句以实现这一目标的正确方法。这是我的声明:

System.out.println ((studentAns.indexOf(ans) + 1) + "\t" + correct + "\t" + incorrect);

这就是我的标题:

for (String heading : headings)                
  {
     System.out.printf ("%8s\t", heading);
  }

就数字而言,它保持均匀的间距,但不与标题对齐。新程序员在这里 - 非常感谢您的所有帮助。谢谢!

【问题讨论】:

  • 如果您的标题比“制表位”长,它将失败。查找如何使用 printf 进行固定宽度字段。
  • 如果对您有帮助,请接受答案。到目前为止,您尚未接受您提出的 5 个问题的任何答案。

标签: java formatting printf


【解决方案1】:

这是对齐表格中的事物的一种方法,

// This will create a String of `i` spaces.
private static String getSpaces(int i) {
  StringBuilder sb = new StringBuilder();
  for (int t = 0; t < i; t++) {
    sb.append(' ');
  }
  return sb.toString();
}

public static void main(String[] args) {
  String[] heading = new String[] { "Student",
      "Correct", "Incorrect" };
  int[][] data = new int[][] {
      new int[] { 1, 3, 7 }, new int[] { 2, 4, 6 },
      new int[] { 3, 8, 2 } };
  System.out.printf("%10s %10s %10s\n", heading[0],
      heading[1], heading[2]);
  for (int[] arr : data) {
    // Shift each data element right by the half the heading string length
    System.out.printf("%10s %10s %10s\n",
        String.valueOf(arr[0])
            + getSpaces(heading[0].length() / 2),
        String.valueOf(arr[1])
            + getSpaces(heading[1].length() / 2),
        String.valueOf(arr[2])
            + getSpaces(heading[2].length() / 2));
  }
}

输出是

 Student    Correct  Incorrect
    1          3         7    
    2          4         6    
    3          8         2    

【讨论】:

    猜你喜欢
    • 2023-02-01
    • 1970-01-01
    • 2019-08-11
    • 2019-11-22
    • 2012-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-12
    相关资源
    最近更新 更多