Java文本格式不正确
我似乎不知道如何让java正确格式化我的输出。输出的代码是:Java文本格式不正确,java,Java,我似乎不知道如何让java正确格式化我的输出。输出的代码是:System.out.format(“\n%1s%20s%25s”、intDf.format(i)、df.format(monthlyPayment)、df.format(totalPayment));输出如下所示: 利率月付款总额 5 188.71 11322.74 5.125 189.29 11357.13 5.25
System.out.format(“\n%1s%20s%25s”、intDf.format(i)、df.format(monthlyPayment)、df.format(totalPayment))
;输出如下所示:
利率月付款总额
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
8202.76 12165.84
我希望所有的值都排列在对应行的第一个字母处。感谢您的帮助,谢谢 很明显,第一列的宽度超过一个字符。所以当你说
System.out.format("\n %1s
那就把它扔了。列名“利率”为13个字符。所以试试看
System.out.format("\n %14s
编辑
根据你的评论,我会使用DecimalFormat
和NumberFormat
等
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]));
}
我把它从
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”
,以便将值放到左侧,实际上我只需将其设置为%-5,然后它就排列好了,感谢您的建议,尽管它让我对System.out.format的工作方式有了更好的了解,并帮助我找到了answer@user2636072我添加了一个更完整的示例。
System.out.format("\n %1s%20s%25s", intDf.format(i), df.format(monthlyPayment), df.format(totalPayment));