【问题标题】:How do I format a list of Strings in Java from a TreeMap to print this way?如何从 TreeMap 格式化 Java 中的字符串列表以以这种方式打印?
【发布时间】:2013-03-09 22:33:43
【问题描述】:

我在 TreeMap 中制作了一个字符串列表,以跟踪一群学生的成绩。现在我的程序正在打印这样的字符串列表:

Jimmy: C+
Tim: A
Samantha: B-
Mike: A-

当我希望它像这样打印出来时:

Jimmy:    C+
Tim:      A
Samantha: B-
Mike:     A-

如何让姓名和成绩以这样的间隔排列?这是我打印出所有内容的代码部分:

//Print all students with their grades
case "P": System.out.println();
          for(Map.Entry<String, String> entry : grades.entrySet())
          {
             System.out.println(entry.getKey() + ":  " + entry.getValue());
          }
          System.out.println();
          break;

【问题讨论】:

  • 在 System.out.println(..) 中使用\t ??

标签: java string format treemap spacing


【解决方案1】:

最简单的解决方案可能是在打印语句中使用制表符而不是空格。

System.out.println(entry.getKey() + ":\t" + entry.getValue());

另一种方法是使用 String format 方法在学生姓名的右侧填充空格。以下代码将在 10 个字符宽的列中打印学生的姓名。如果您在打印报告之前知道姓名的最大长度(您应该能够轻松找到),这将更加可靠。

String name = "Tim:";
String student = String.format("%1$-10s", name);
System.out.println(student + "A");

【讨论】:

    【解决方案2】:

    您可以查看使用 System.out.format 和不同格式选项(例如右对齐等)的选项。只需 google 一下。这是一个link你看看

    【讨论】:

      【解决方案3】:

      你想左填充字符串。 看看这个答案:How can I pad a String in Java?

      您可能还需要一个函数来计算您尝试输出的所有名称的最大长度。就像是。

      private int maxLength(Collection<String> names) {
              int max = 0;
              for (String s : names) {
                  if (s.length() > max) {
                      max = s.length();
                  }
              }
              return max;
          }
      

      然后,像这样使用它:maxLength(grades.keySet());

      【讨论】:

        【解决方案4】:

        将此输入到循环中的System.out.println()

        String.format("%-10s %s", entry.getKey()+":", entry.getValue());
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2020-08-05
          • 1970-01-01
          • 1970-01-01
          • 2022-07-11
          • 1970-01-01
          • 2010-11-10
          • 1970-01-01
          相关资源
          最近更新 更多