我对我的学校项目有点问题。我们应该写一个贷款类,它会做一些与贷款有关的事情,比如退还月付款和贷款总额。我的问题是我有这个代码的具体说明,我绝对不能去。 这是代码:
import java.util.Scanner;
import java.text.DecimalFormat;
import java.lang.Math;
public class Loan
{
public double annualInterestRate = 0;
public int numberOfYears = 0;
public double loanAmount = 0;
public Loan()
{
annualInterestRate = 0.025;
numberOfYears = 1;
loanAmount = 1000;
}
public Loan(double interestRate, int numYears, double amount)
{
setRate(interestRate);
setYears(numYears);
setLoanAmount(amount);
}
public void setRate(double interest)
{
DecimalFormat percent = new DecimalFormat( "0.0%" );
if(interest > 25 || interest < 0)
{
System.out.println("WARNING: Invalid annual interest rate: " + percent.format(interest) + ".");
System.out.println("Current value not changed: " + percent.format(annualInterestRate * 100) + ".");
}
else
{
annualInterestRate = interest;
}
}
public void setYears(int years)
{
if(years > 30 || years <= 0)
{
System.out.println("WARNING: Invalid number of years: " + years + ".");
System.out.println("Current value not changed: " + numberOfYears + ".");
}
else
{
numberOfYears = years;
}
}
public void setLoanAmount(double amnt)
{
DecimalFormat loan = new DecimalFormat( "$#,##0.00" );
if(amnt <= 0)
{
System.out.println("WARNING: Invalid loan amount: " + loan.format(amnt) + ".");
System.out.println("Current value not changed: " + loan.format(amnt) + ".");
}
else
{
loanAmount = amnt;
}
}
public double getAnnualInterestRate()
{
return annualInterestRate;
}
public int getNumberOfYears()
{
return numberOfYears;
}
public double getLoanAmount()
{
return loanAmount;
}
public double getMonthlyPayment()
{
double monthly = annualInterestRate/12;
double monthlyPayment = (loanAmount * monthly)/1 - (1/(1 + monthly));
monthlyPayment = Math.pow(monthlyPayment, 12);
return monthlyPayment;
}
public double getTotalPayment()
{
double totalPayment = getmonthlyPayment() * 12;
return totalPayment;
}
public String toString()
{
DecimalFormat percent = new DecimalFormat( "0.0%" );
DecimalFormat loan = new DecimalFormat( "$#,##0.00" );
String interestRate = percent.format(annualInterestRate);
String numOfYears = Integer.toString(numberOfYears);
String loanAmnt = loan.format(loanAmount);
String total = "Annual Interest Rate:\t" + interestRate + "\nNumber of Years:\t\t" + numOfYears + "\nLoan Amount:\t\t\t" + loanAmnt;
return total;
}
}
我的问题在于getTotalPayment方法。如果没有我将monthlyPayment声明为字段,例如annualInterestRate,或者将其传递给getTotalPayment方法,它就无法访问monthlyPayment变量。问题是,getTotalPayment不允许有参数,并且我们不允许拥有比她指示我们拥有的三个字段更多的字段,这三个字段是你在开头看到的三个字段。码。 所以,我的问题是:有没有办法让getPotalPayment可以访问变量monthlyPayment,而不是将monthlyPayment作为字段或给getTotalPayment一个参数?
答案 0 :(得分:1)
您的getTotalPayment()
方法存在拼写错误。
当您应该致电getmonthlyPayment()
时,您尝试做的是调用方法getMonthlyPayment()
。
如果你想要一个大写的'M',你错过了我的答案中的suttle差异你有一个小写'm'。
我不完全确定这是否是您的问题,但它是我的IDE告诉我的唯一语法错误。
答案 1 :(得分:0)
在修改后的代码中,您需要在调用M
时使用大写getMonthlyPayment()
。