Java在我的抵押贷款计算器上输入利率



我做了一个代码来计算每月的抵押贷款付款。这是我的代码>的一部分

public static void printAmortizationSchedule(double principal, double annualInterestRate,
int numYears) {
double interestPaid, principalPaid, newBalance;
double monthlyInterestRate, monthlyPayment;
int month;
int numMonths = numYears * 12;
monthlyInterestRate = annualInterestRate / 12;
monthlyPayment      = monthlyPayment(principal, monthlyInterestRate, numYears);
System.out.format("Your monthly Payment is: %8.2f%n", monthlyPayment);
for (month = 1; month <= numMonths; month++) {
// Compute amount paid and new balance for each payment period
interestPaid  = principal      * (monthlyInterestRate / 100);
principalPaid = monthlyPayment - interestPaid;
newBalance    = principal      - principalPaid;
// Update the balance
principal = newBalance;
}
}
static double monthlyPayment(double loanAmount, double monthlyInterestRate, int numberOfYears) {
monthlyInterestRate /= 100;  
return loanAmount * monthlyInterestRate /
( 1 - 1 / Math.pow(1 + monthlyInterestRate, numberOfYears * 12) );
}

现在,我需要添加代码 1.本金金额必须是非负数。

  1. 按揭付款将由以下金额之一决定:

• 1年 3.5% • 2年 3.9% • 3年 4.4% • 5年 5.0% • 10年 6.0%

我想我需要使用 do while 语句,或者如果其他代码。但是,我正在努力寻找放置的位置。请帮帮我!

在这两种情况下,您都在处理一个条件:

  • 如果本金金额为负数,不要执行计算,否则,继续计算。
  • 如果抵押贷款是N年,使用R利率。

因此,您将使用 if-then-else 构造。

对于本金金额,请尽早检查;执行计算只是因为它们无效而将其全部丢弃是没有意义的。您可以引发异常来指示无效输入,即负主体。

对于费率,您只需要确保在使用之前选择正确的费率(使用if-then-else(。

最新更新