2011-04-28 83 views
2

我有一些格式化輸出文件給自己,以便易於閱讀。我試圖輸出文件如:Java輸出文件格式化

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

但我有麻煩。目前我使用下面的代碼得到下面的輸出:

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

這給了我:

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

因爲我剛剛從大學名稱的末尾填充。無論如何填充整個字符串,所以所有的字符串都是恆定的長度?

謝謝大家對你幫助

回答

4

是的,輸出你的大學名稱左對齊,填充到一定長度,然後輸出你的學生數量右對齊,並填充到一定長度:

fmt.format("%-20s%10d\n", colleges[i].nameOfSchool, (int) colleges[i].numOfStudents); 
2

您可能要添加的學校名稱過於格式化,如下所示:

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

下面的鏈接可以給你在格式更深入的瞭解: http://download.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html

+1

我認爲應該是''%1 $ 20s%2 $ 5d \ n「'。 – Mac 2011-04-28 22:23:17

+0

是的,你是對的。 – 2011-04-28 22:33:19