有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java:如何正确证明$?

以下是我得到的:

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和15个空格,这是怎么做到的?我想要这样:

Gross Amount:            $3575.00

提前谢谢


共 (1) 个答案

  1. # 1 楼答案

    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** 
    

    字符串格式背后的想法是,你正在构建一个字符串,然后通过字符串的参数向其中添加字符。格式化和打印。希望这有帮助