1

我正在尝试格式化文件输出,以便所有内容都排列整齐,并且几乎可以正常工作。我已经使用 \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
4

3 回答 3

2

也许你可以像这样使用:

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()));

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

于 2013-05-29T21:19:26.690 回答
1

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

out.printf("%14s:  %14s  %14s", 
             newTeam.getTeamName(), newTeam.getBatAvgStr(),  
                newTeam.getSlugAvgStr());
于 2013-05-29T21:18:38.380 回答
0

尝试使用 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*
*/

在这里得到了回答:字符串垫

于 2013-05-29T21:17:57.467 回答