Java output file formatting
Solution 1
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);
Solution 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
Brendan Lesniak
Working as a Software Engineer in the Quality Management and Contact Center space. In my free time I like to work on a wide variety of projects, from Legacy Swing applications, to Web Apps, to Embedded Systems.
Updated on June 14, 2022Comments
-
Brendan Lesniak almost 2 years
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
-
Mac about 13 yearsI believe that should be
"%1$20s %2$5d\n"
.