2

I am having a bit of trouble formatting an output file for myself to be easily readable. I am trying to output the file such as:

Name of School                   Size of School
--------------                   --------------
Blblah blah                        1300
Blah blah blah                    11300
Blah blah blah asdf               14220
Blah bblah                         1300

but am having trouble. Currently I am using the following code to get the following output:

File file1 = new File("src\\sortedInt.txt");
Formatter fmt = new Formatter(file1);

HelperMethods.quickSortStudents(colleges, 0, colleges.length - 1);
for(int i = 0; i < colleges.length; i++)
{
      fmt.format(colleges[i].nameOfSchool + "%20d" + "\n", (int)colleges[i].numOfStudents);
      fmt.flush();
}  

which gives me:

eastman school of music                 800
clark university                1100
walla walla college                1100
drew                1200
juilliard                1200

Because I am just padding from the end of the college name. Is there anyway to pad the whole string so all the strings are a constant length?

Thank you everyone for you help

2 Answers 2

4

Yep, output your college name left-justified and padded to a certain length, then output your number of student right-justified and padded to a certain length:

fmt.format("%-20s%10d\n", colleges[i].nameOfSchool, (int) colleges[i].numOfStudents);
Sign up to request clarification or add additional context in comments.

Comments

2

You might want to add the name of the schools to be formatted too, as the following:

fmt.format("%1$20s %1$5d\n", colleges[i].nameOfSchool, (int)colleges[i].numOfStudents);

The following link can give you more insight in formatting: http://download.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html

1 Comment

I believe that should be "%1$20s %2$5d\n".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.