對準

2015-05-12 22 views
3

我的代碼是這樣的:對準

// for loop for displaying multiple values 
for (int index = 0; index < 5; index++) { 

    System.out.println("\t\t" + name[index] + "\t\t\t" + "$" + sales[index] + "\t\t\t" + "$" + comm[index] + " "); 
} 

這是電流輸出,但我想用同樣的間距

   Sales and Commission 
    ====================================================== 
    Salesperson  Sales Amount  Commission 
    ----------------------------------------------------- 
    u ujuhygtfd   $89000   $8900.0 
    uh uh   $87000   $8700.0 
    t t   $65000   $5200.0 
    f f   $54000   $4320.0 
    u r   $43000   $2580.0 

    Total: 9 Data entries 

顯示輸出如何顯示我的數據,如這個?

   Sales and Commission 
    ====================================================== 
    Salesperson  Sales Amount  Commission 
    ----------------------------------------------------- 
    u ujuhygtfd   $89000   $8900.0 
    uh uh    $87000   $8700.0 
    t t     $65000   $5200.0 
    f f     $54000   $4320.0 
    u r     $43000   $2580.0 

    Total: 9 Data entries 
+0

通常添加語言標記會很有幫助。在這種情況下,我假設Java? – chancea

+0

如果有更好的方法(可能有),我不會這樣做,但是你可以測試你的字符串的大小,例如所有Salesperson的字符串必須是10個字符長,所以如果你的字符串只有4你會添加6'空格' –

+0

@ njzk2:當然,但它是一個確切的重複?另請參閱http://blog.stackoverflow.com/2010/11/dr-strangedupe-or-how-i-learned-to-stop-worrying-and-love-duplication/ –

回答

2

至於說in this answer(略有修改):

使用System.out.format。可以設置字段的長度是這樣的:

System.out.format("%32s%10d%16d", name[index], sales[index], comm[index]);

此墊name[index]sales[index]comm[index]至32,10和16個字符,分別 。

見的Javadoc java.util.Formatter用於在 語法的更多信息(System.out.format內部使用一個Formatter)。

+1

格式化字符串的另一個好處是他們更容易閱讀通常。 '(「姓名:」+姓名+「佣金:」+金額)'與'(「姓名:%s佣金:%d」,姓名,金額)''''''''''我的例子中的第一個字符串可以讀取'「Name:CaptainManCommission:100」',但很難立即告訴。 –

0

你可以做類似

for (int index = 0; index < 5; index++) { // for loop for displaying multiple values 
     int numOfSpaces = 20 - name[index].length(); 
     String spaces = ""; 
     for (int i = 0; i<numOfSpaces; i++) 
      spaces += " "; 
     System.out.println("\t\t" + name[index] + spaces + "$" + sales[index] + "\t\t\t" + "$" + comm[index] + " "); 
    } 

並更改任意20到任何你想要的,如。姓名中最長的字符串+ 5.

+0

非常感謝你解決了我的問題..非常感謝.. –

+0

還有一個問題請 –