1

I am trying to format a file output so that everything is lined up nicely, and its almost working. I've used \t to try to give the output a uniform rigid look. It is almost there, but it isn't quite working for one (see below) I think it is because the team name is too short, but I'm not sure any suggestions?

My Code:

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

my output:

2011 Regular Season

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

3 Answers3

2

Maybe you can use smth like :

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

But I didn't test it, so I'm not really sure...

Kooki
  • 1,115
  • 7
  • 29
1

This is occurring to the fact that "Texas" has too few letter to offset the first tab in line with the others. Assuming that you're using PrintWriter, you could use printf rather than println and use format specifiers to pad the String tokens:

out.printf("%14s:  %14s  %14s", 
             newTeam.getTeamName(), newTeam.getBatAvgStr(),  
                newTeam.getSlugAvgStr());
Reimeus
  • 152,723
  • 12
  • 195
  • 261
0

Try Using String.Format();

Example:

>     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*
*/

Was answered here: String Pad

Community
  • 1
  • 1
Si8
  • 8,578
  • 20
  • 88
  • 201