格式化我的代码以正确显示表格时出现问题,我不确定如何修复它。基本上,第一行数字未正确对齐以形成其他列。如何在利率下的数字末尾添加符号“%”? 抱歉,我试图在这里显示输出的样子,但我无法正确显示。
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);
}
}
}
答案 0 :(得分:1)
第一列的错位是由于“总付款”标题末尾的换行符造成的。它需要位于格式字符串的末尾。
由于利率的左对齐,您需要创建一个用%符号格式化的中间字符串,然后左对齐。
我相信这段代码应该有用。
const cars = Object.values(carsinfo.cars).map((val) => ({ name: Object.keys(val)[0] }));
console.log('name: ', cars[0].name);
输出:
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);
}
}
答案 1 :(得分:0)
Double %%
将在输出中获得单个%
- 我还注意到它修复了数字列上的左缩进:
System.out.printf("%-20.3f%% %-20.2f%% %-20.2f%%\n", interestRate,
monthlyPayment, totalPayment);