能否提供一个Java代码示例来计算房贷还款?
时间: 2024-10-03 10:01:11 浏览: 46
当然可以。下面是一个简化的Java代码示例,用于计算每月等额本息还款,假设月利率固定不变:
```java
import java.util.Scanner;
public class MortgageCalculator {
private double loanAmount;
private double annualInterestRate;
private int loanTermInYears;
private double monthlyInterestRate;
private double monthlyPayment;
private double remainingBalance;
public MortgageCalculator(double loanAmount, double annualInterestRate, int loanTermInYears) {
this.loanAmount = loanAmount;
this.annualInterestRate = annualInterestRate / 100; // 将年利率转换为小数形式
loanTermInYears *= 12; // 转换为月
monthlyInterestRate = annualInterestRate / 12;
calculateMonthlyPayment();
}
private void calculateMonthlyPayment() {
double numerator = annualInterestRate * loanAmount;
double denominator = (1 - Math.pow(1 + annualInterestRate, -loanTermInYears));
monthlyPayment = numerator / denominator;
}
public void repayLoan() {
for (int month = 1; month <= loanTermInYears; month++) {
System.out.printf("第%02d个月:月还款额 %.2f 元\n", month, monthlyPayment);
remainingBalance -= monthlyPayment;
if (remainingBalance < 0.0001) { // 当剩余余额接近0时停止
break;
}
monthlyPayment = calculateMonthlyPayment(); // 刷新月供,因为剩余本金会影响实际利息
}
System.out.println("贷款已还清!");
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入贷款金额:");
double loanAmountInput = scanner.nextDouble();
System.out.print("请输入年利率(百分比):");
double interestRateInput = scanner.nextDouble();
System.out.print("请输入贷款期限(年):");
int termInYearsInput = scanner.nextInt();
MortgageCalculator mortgage = new MortgageCalculator(loanAmountInput, interestRateInput, termInYearsInput);
mortgage.repayLoan();
}
}
```
阅读全文