我在格式化代码以正确显示表格时遇到问题,但我不知道如何修复它。基本上,第一行数字没有正确对齐,无法像其他数字一样形成列。如何在利率下的数字末尾添加符号“%”? 抱歉,我试图在此处显示输出的样子,但无法正确显示。
public class Boo {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Loan amount: ");
double loanAmount = in.nextInt();
System.out.println("Number of years: ");
int year = in.nextInt();
double monthlyPayment = 0;
double interestRate = 5.0;
final double INCREMENT = 0.125;
System.out.printf("%-20s %-20s %-20s", "Interest Rate", "Monthly Payment", "Total Payment\n");
for (int i = 0; i < year; i++) {
interestRate += INCREMENT; //increment by 0.125 every year
double monthlyInterestRate = interestRate / 1200;
monthlyPayment = loanAmount * monthlyInterestRate / (1 - 1 / Math.pow(1 + monthlyInterestRate, year * 12));
double totalPayment = monthlyPayment * year * 12;
System.out.printf("%-20.3f %-20.2f %-20.2f\n", interestRate, monthlyPayment, totalPayment);
}
}
}
最佳答案
第一列未对齐是由于“总付款”标题末尾的换行符造成的。它需要位于格式字符串的末尾。
由于利率左对齐,您需要创建一个中间字符串,使用 % 符号格式化,然后左对齐。
我相信这段代码应该可以工作。
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Loan amount: ");
double loanAmount = in.nextInt();
System.out.println("Number of years: ");
int year = in.nextInt();
double monthlyPayment = 0;
double interestRate = 5.0;
final double INCREMENT = 0.125;
System.out.printf("%-20s %-20s %-20s\n", "Interest Rate", "Monthly Payment", "Total Payment");
for (int i = 0; i < year; i++)
{
interestRate += INCREMENT; // increment by 0.125 every year
double monthlyInterestRate = interestRate / 1200;
monthlyPayment = loanAmount * monthlyInterestRate / (1 - 1 / Math.pow(1 + monthlyInterestRate, year * 12));
double totalPayment = monthlyPayment * year * 12;
System.out.printf("%-20s %-20.2f %-20.2f\n", String.format("%.3f%%", interestRate), monthlyPayment, totalPayment);
}
}
输出:
Loan amount:
567
Number of years:
5
Interest Rate Monthly Payment Total Payment
5.125% 10.73 643.95
5.250% 10.77 645.90
5.375% 10.80 647.86
5.500% 10.83 649.82
5.625% 10.86 651.79
关于java - 为什么这个 `printf` 格式的表的第一行没有对齐?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45259603/