本关任务:编写一个程序,由用户输入住房贷款和贷款年限,程序输出不同利率下的月还款额和总还款额,利率从 5%~8%,增长间隔为 1/8。例如,如果输入贷款额 10000 元人民币,贷款期限 5 年,程序应输出如下内容:用java
时间: 2024-10-21 10:16:07 浏览: 93
LoanCalculator:该贷款计算器将帮助您确定贷款的每月还款额。 只需在下面的字段中输入要偿还的贷款金额,利率和年数,然后单击计算
在Java中编写这个程序,你可以创建一个简单的类`LoanCalculator`,它包含计算月还款额和总还款额的方法。这里是一个基础的示例:
```java
import java.util.Scanner;
class LoanCalculator {
private double loanAmount;
private int loanTermYears;
private double interestRates[] = {0.05, 0.06, 0.07, 0.08}; // 利率数组
public LoanCalculator(double loanAmount, int loanTermYears) {
this.loanAmount = loanAmount;
this.loanTermYears = loanTermYears;
}
public void calculateMonthlyPayment(double rate) {
double monthlyRate = rate / 1200; // 将年利率转换为月利率
double monthlyPayment = loanAmount * monthlyRate / (1 - Math.pow(1 + monthlyRate, -loanTermYears * 12));
System.out.printf("利率 %.1f%% 时,月还款额:%.2f 元,总还款额:%.2f 元\n", rate, monthlyPayment, monthlyPayment * loanTermYears * 12);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入贷款金额(元):");
double loanAmount = scanner.nextDouble();
System.out.println("请输入贷款期限(年):");
int loanTermYears = scanner.nextInt();
LoanCalculator calculator = new LoanCalculator(loanAmount, loanTermYears);
for (double rate : interestRates) {
calculator.calculateMonthlyPayment(rate);
}
scanner.close();
}
}
```
在这个程序中,用户首先输入贷款金额和贷款期限,然后计算器会遍历给定的利率数组,对于每个利率计算月还款额和总还款额,并打印出来。
阅读全文