日期:2014-05-20 浏览次数:20840 次
/**
* 计算贷款。
*/
package Ten;
import java.util.Date;
import java.util.Scanner;
public class TestLoanClass {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter yearly interest rate, for example, 8.25: ");
double annualInterestRate = input.nextDouble();
System.out.print("Enter number of yearr as an integer: ");
double numberOfYears = input.nextDouble();
/*
* 下列代码中的loanAmount显示错误。
* Exception in thread "main" java.lang.Error: Unresolved compilation problem:
* Cannot make a static reference to the non-static field loanAmount
*
*/
TestLoanClass loan = new TestLoanClass(annualInterestRate, numberOfYears, loanAmount);
System.out.printf("The loan was created of %s\n" +
"The monthly payment is %.2f\nThe total payment is %.2f\n",
loan.getLoanDate().toString(), loan.getMonthlyPayment(), loan.getTotalPayment());
}
private double annualInterestRate;
private int numberOfYears;
private double loanAmount;
private Date loanDate;
public TestLoanClass(){
this(2.5, 1, 1000);
}
public TestLoanClass(double annualInterestRate, int numberOfYears, double loanAmount){
this.annualInterestRate = annualInterestRate;
this.numberOfYears = numberOfYears;
this.loanAmount = loanAmount;
loanDate = new Date();
}
public double getAnnualInterestRate(){
return annualInterestRate;
}
public void setAnnualInterestRate(double annualInterestRate){
this.annualInterestRate = annualInterestRate;
}
public int getNumberOfYears(){
return numberOfYears;
}
public void setNumberOfYears(int numberOfYears){
this.numberOfYears = numberOfYears;
}
public double getLoanAmount(){
return loanAmount;
}
public void setLoanAmount(double loanAmount){
this.loanAmount = loanAmount;
}
public double getMonthlyPayment(){
double monthlyInterestRate = annualInterestRate / 1200;
double monthlyPayment = loanAmount * monthlyInterestRate / (1 - (Math.pow(1 / (1 + monthlyInterestRate), numberOfYears * 12)));
return monthlyPayment;
}
public double getTotalPayment(){
double totalPayment = getMonthlyPayment() * numberOfYears * 12;
return totalPayment;
}
public Date getLoanDate(){
return loanDate;
}
}
改为
import java.util.Date;
import java.util.Scanner;
public class TestLoanClass {