Java文本格式不正确

时间:2014-11-29 23:20:47

标签: java

我似乎无法弄清楚如何让java正确地格式化我的输出。输出的代码snipet是:System.out.format("\n %1s%20s%25s", intDf.format(i), df.format(monthlyPayment), df.format(totalPayment));输出如下所示:

Interest Rate Monthly Payment Total Payment 5 188.71 11322.74 5.125 189.29 11357.13 5.25 189.86 11391.59 5.375 190.44 11426.11 5.5 191.01 11460.7 5.625 191.59 11495.35 5.75 192.17 11530.06 5.875 192.75 11564.84 6 193.33 11599.68 6.125 193.91 11634.59 6.25 194.49 11669.56 6.375 195.08 11704.59 6.5 195.66 11739.69 6.625 196.25 11774.85 6.75 196.83 11810.08 6.875 197.42 11845.37 7 198.01 11880.72 7.125 198.6 11916.14 7.25 199.19 11951.62 7.375 199.79 11987.16 7.5 200.38 12022.77 7.625 200.97 12058.44 7.75 201.57 12094.18 7.875 202.17 12129.97 8 202.76 12165.84

我希望所有值都在相应行的第一个字母处排成一行。感谢任何帮助,谢谢!

2 个答案:

答案 0 :(得分:0)

显然,您的第一列超过一个字符宽。所以当你说

System.out.format("\n %1s

抛出它。列名称“利率”为13个字符。所以试试

System.out.format("\n %14s

修改

根据您的评论,我会使用DecimalFormatNumberFormat之类的

String[] headings = { "Interest Rate", "Monthly Payment",
        "Total Payment" };
for (String heading : headings) {
    System.out.print(heading);
    System.out.print("\t");
}
System.out.println();
double[] interestRates = { 5, 5.125 };
double[] monthlyPayments = { 188.71, 189.29 };
double[] totalPayments = { 11322.74, 11357.13 };
NumberFormat interestFormat = new DecimalFormat("#.000'%'");
NumberFormat currencyFormat = NumberFormat.getCurrencyInstance();
for (int i = 0; i < interestRates.length; i++) {
    System.out.printf("%-13s\t%-15s\t%-13s%n",
            interestFormat.format(interestRates[i]),
            currencyFormat.format(monthlyPayments[i]),
            currencyFormat.format(totalPayments[i]));
}

输出

Interest Rate   Monthly Payment Total Payment   
5.000%          $188.71         $11,322.74   
5.125%          $189.29         $11,357.13   

答案 1 :(得分:0)

我从

改变了它
  System.out.format("\n %1s%20s%25s", intDf.format(i), df.format(monthlyPayment), df.format(totalPayment));

System.out.format("\n %-5s%20s%25s", intDf.format(i), df.format(monthlyPayment), df.format(totalPayment));

然后将DecimalFormat更改为:"'$'0.00"