这是我得到的:
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 :(得分: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的参数向它添加字符。希望这会有所帮助。