对于给定的贷款额,月支付额包括偿还本金及利息。月利息是通过月利率乘以余额(剩余本金)计算出来的。
注意:最后一次偿还后,余额可能不为0,如果不为0的话,最后一个月支付额应当是正常的月支付额加上最后的余额。
提示:编写一个循环来打印该表,由于每个月的还款额都是相同的,因此应当在循环之间开始它。开始时,余额就是贷款总额。在循环的每次迭代中,计算利息及本金,然后更新余额。
编写一个程序,让用户输入贷款总额年限利率,然后显示分期还贷时间表。
package pack2;
import java.util.Scanner;
public class LoanTimetable {
public static void main(String[] args) {
try(Scanner input = new Scanner(System.in);) {
System.out.print(" Loan Amount: ");
double amount = input.nextDouble();
System.out.print(" Number of Years: ");
int year = input.nextInt();
System.out.print(" Annual Interest Rate: ");
double annualInterestRate = input.nextDouble();
showLoanTimetable(amount, year, annualInterestRate);
}
}
//显示分期还贷时间表
public static void showLoanTimetable(double balance, int numberOfYears,
double annualInterestRate) {
double monthlyRate = annualInterestRate / 1200;
double monthlyPayment = monthlyPayment(balance, monthlyRate, numberOfYears);
System.out.printf("\n Monthly Payment: %.2f\n", monthlyPayment);
System.out.printf(" Total Payment: %.2f\n\n", totalPayment(numberOfYears,
monthlyPayment));
System.out.println(" Payment#\tInterest\tPrincipal\tBalance");
for (int i = 1; i <= numberOfYears * 12; i++) {
double interest = monthlyRate * balance;
double principal = monthlyPayment - interest;
balance -= principal;
System.out.printf(" %-6d%14.2f%17.2f\t%15.2f\n", i, interest, principal,
balance);
}
}
//月支付额
public static double monthlyPayment(double amount, double rate, int year) {
return amount * rate / (1 - 1 / Math.pow(1 + rate, year * 12));
}
//总支付额
public static double totalPayment(int year, double monthlyPayment) {
return monthlyPayment * 12 * year;
}
}