练习-Java循环综合练习一之住房贷款还款计算
时间: 2024-09-19 07:03:12 浏览: 116
在Java中,我们可以创建一个简单的程序来进行住房贷款还款计算的练习。这个综合练习通常涉及到循环,比如for循环或while循环,以及基本的数学运算。下面是一个基础的示例:
```java
class MortgageCalculator {
// 假设固定利率贷款
private double interestRate;
private int loanAmount;
private int years;
private double monthlyPayment;
public MortgageCalculator(double interestRate, int loanAmount, int years) {
this.interestRate = interestRate / 100; // 将百分比转换为小数
this.loanAmount = loanAmount;
this.years = years;
calculateMonthlyPayment();
}
private void calculateMonthlyPayment() {
double totalPayments = years * 12;
monthlyPayment = (loanAmount * interestRate * (1 + interestRate) ** totalPayments) / ((1 + interestRate) ** totalPayments - 1);
}
public double getMonthlyPayment() {
return monthlyPayment;
}
public static void main(String[] args) {
MortgageCalculator mortgage = new MortgageCalculator(4.5, 500000, 20); // 示例贷款,年利率4.5%,贷款金额50万,期限20年
System.out.println("每月应还贷款额为:" + mortgage.getMonthlyPayment() + "元");
}
}
```
在这个例子中,我们首先定义了一个MortgageCalculator类,它有利息率、贷款金额、贷款年限等属性,并有一个方法`calculateMonthlyPayment()`用于计算月供。`main`函数展示了如何实例化这个类并打印出每月还款额。
阅读全文