Loan(double,int,double)方法是否为贷款类型未定义?

时间:2011-11-23 15:56:38

标签: java exception-handling

任何人都可以帮我看看我错过了哪里吗?我试图让贷款类调用main方法,并检查我的异常处理是否正确。我对此非常陌生,确切地说是第六周,并且可以使用所有可能的建设性帮助。提前谢谢!

package loan;
import java.util.Scanner;

public class Loan {

public static void main(String[] args) {
    try {
        Loan(2.5, 0, 1000.00);
    }
    catch (IllegalArgumentException ex) {
        ex.getMessage();
    }
}

Scanner input = new Scanner(System.in);
double annualInterestRate;
int numberOfYears;
double loanAmount;
private java.util.Date loanDate;

public Loan() {
    this(2.5, 0, 1000);
}
public Loan(double annualInterestRate, int numberOfYears, double loanAmount) {
    this.annualInterestRate = annualInterestRate;
    this.numberOfYears = numberOfYears;
    this.loanAmount = loanAmount;
    loanDate = new java.util.Date();
}


public double getAnnualInterestRate() {
    if (annualInterestRate > 0)
        return annualInterestRate;
    else
        throw new IllegalArgumentException("Interest rate cannot be zero or negative.");
}

public void setAnnualInterestRate(double annualInterestRate) {
    this.annualInterestRate = annualInterestRate;
}

public int getNumberOfYears() {
    if (numberOfYears > 0)
        return numberOfYears;
    else
        throw new IllegalArgumentException("Number of years cannot be zero");
}

public void setNumberOfYears(int numberOfYears) {
    this.numberOfYears = numberOfYears;
}

public double getLoanAmount() {
    if (loanAmount > 0)
        return loanAmount;
    else
        throw new IllegalArgumentException("Loan amount cannot be zero");
}

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 java.util.Date getLoanDate() {
    return loanDate;
}
}

4 个答案:

答案 0 :(得分:3)

目前尚不清楚您希望在main中做什么:

try {
    Loan(2.5, 0, 1000.00);
}

我怀疑你认为它是一个构造函数调用:

try {
    new Loan(2.5, 0, 1000.00);
}

您的帖子表明对术语有点混淆,这可能导致了这个问题:

  

我正在尝试将贷款类调用到主方法

你没有调用一个类。您可以调用构造函数或方法。你的意思是:

  

我试图让main方法调用Loan类的构造函数。

此时,您需要new可能更清楚。

答案 1 :(得分:2)

您需要先使用“new”关键字创建贷款对象。这将调用构造函数。

Loan loanVar = new Loan(2.5, 0, 1000.00);

答案 2 :(得分:1)

要在main方法中调用构造函数,您需要使用new关键字。就像你在Loan构造函数中初始化loanDate一样。

答案 3 :(得分:1)

您的代码尝试调用名为Loan的静态方法,但看起来您想要创建一个新的Loan对象。您可以使用关键字new并将正确的参数提供给构造函数来执行此操作:

// create a new Loan using the no-args constructor
Loan defaultLoan = new Loan();
// or create a new Load with the specified rate/duration/amount
Loan myLoan = new Loan(2.5, 0, 1000.0);