2015-02-10 56 views
0

這是我的了:

outputStr = name + "\n" + "Gross Amount:$ " + String.format("%.2f", grossAmount) + "\n" 
      + "Federal Tax:$ " + String.format("%.2f", fedIncomeTax) + "\n" + "State Tax:$ " 
      + String.format("%.2f", stateTax) + "\n" + "Social Security Tax:$ " + String.format("%.2f", ssTax) 
      + "\n" + "Medicare/Medicaid Tax:$ " + String.format("%.2f", medicareTax) + "\n" + "Pension Plan:$ " 
      + String.format("%.2f", pensionPlan) + "\n" + "Health Insurance:$ " + String.format("%.2f", HEALTH_INSURANCE) 
      + "\n" + "Net Pay:$ " + String.format("%.2f", netPay); 
    System.out.println(outputStr); 

它打印出這樣的:

Random Name 

Gross Amount:$ 3575.00 

Federal Tax:$ 536.25 

等等......

但我想右對齊$和變量15個空格正確的,這是如何完成的?我想這樣的:提前

Gross Amount:   $3575.00 

謝謝...

+0

我可以通過使用「%15.2f」而不是$ – Marcus 2015-02-10 17:53:53

回答

2

printf的一個好的執行,在這裏,但字符串格式應該符合您的需求。

// This will give it 20 spaces to write the prefix statement and then the 
//space left will be "tacked" on as blank chars. 
String.format("%-20s",prefixStatement); 

//Below is the printf statement for exactly what you want. 
System.out.printf("%-20s$%.2f\n","Gross Amount:",3575.00); 
//This executes and returns: **Gross Amount:  $3575.00** 

//Below will get you fifteen spaces every time. 
String ga = "Gross Amount:"; 
System.out.printf("%-"+(ga.length()+15)+"s$%d\n","Gross Amount:",2); 
//This executes and returns: **Gross Amount:    $2** 

背後字符串格式化的想法是,你正在構建一個字符串,然後在文字後通過的String.format和printf的參數添加到它。希望這可以幫助。

+0

得到輸出到右對齊我有變量計算。我看到你把號碼放在那裏。我只是把變量名放在那裏?爲你的第二個解決方案 – Marcus 2015-02-10 18:19:34

+0

沒關係,我想通了。感謝您的幫助,第二個解決方案效果很好! – Marcus 2015-02-10 18:23:59