【问题标题】:Using \t to line up a file output使用 \t 排列文件输出
【发布时间】:2013-05-25 07:14:39
【问题描述】:

我正在尝试格式化文件输出,以便所有内容都排列整齐,并且几乎可以正常工作。我已经使用 \t 来尝试使输出具有统一的刚性外观。它几乎就在那里,但它对一个人不太有效(见下文)我认为这是因为团队名称太短,但我不确定有什么建议?

我的代码:

while ((str = in.readLine()) != null) {
            Team newTeam = new Team(str);
            teamArray[counter] = newTeam;
            out.println(newTeam.getTeamName() + ": "+ "\t"  + newTeam.getBatAvgStr() + " " + newTeam.getSlugAvgStr());

我的输出:

2011 常规赛

TEAM              BA   SA
Boston:         .280 .461
NY_Yankees:     .263 .444
Texas:  .283 .460
Detroit:        .277 .434
St.Louis:       .273 .425
Toronto:        .249 .413
Cincinnati:     .256 .408
Colorado:       .258 .410
Arizona:        .250 .413
Kansas_City:    .275 .415

【问题讨论】:

    标签: java file-io spacing


    【解决方案1】:

    也许你可以像这样使用:

    while ((str = in.readLine()) != null) 
    {
            Team newTeam = new Team(str);
            teamArray[counter] = newTeam;
            out.println(String.format("%1$-20s : %2$-5s %3$-5s",newTeam.getTeamName(), newTeam.getBatAvgStr(), newTeam.getSlugAvgStr()));
    

    但我没有测试它,所以我不太确定......

    【讨论】:

    • 这太棒了!!非常感谢
    【解决方案2】:

    这是因为“Texas”的字母太少而无法将第一个选项卡与其他选项卡对齐。假设您使用的是PrintWriter,您可以使用printf 而不是println,并使用格式说明符填充String 标记:

    out.printf("%14s:  %14s  %14s", 
                 newTeam.getTeamName(), newTeam.getBatAvgStr(),  
                    newTeam.getSlugAvgStr());
    

    【讨论】:

      【解决方案3】:

      尝试使用 String.Format();

      例子:

      >     public static String padRight(String s, int n) {
      >          return String.format("%1$-" + n + "s", s);  
      >     }
      >     
      >     public static String padLeft(String s, int n) {
      >         return String.format("%1$" + n + "s", s);  
      >     }
      >     
      >     ...
      >     
      >     public static void main(String args[]) throws Exception {
      >      System.out.println(padRight("Howto", 20) + "*");
      >      System.out.println(padLeft("Howto", 20) + "*");
      >     }
      
      /*
        output :
           Howto               *
                          Howto*
      */
      

      在此回答:String Pad

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-12
        相关资源
        最近更新 更多