2011-11-23 85 views
0

任何人都可以幫助我看到我錯過了這個?我正在嘗試獲取調用main方法的貸款類,並檢查我的異常處理是否正確。我對此非常陌生,準確的說,第六週可以使用所有可能的建設性幫助。提前致謝!Loan類型的Loan(double,int,double)方法未定義?

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; 
} 
} 
+0

您能發佈實際錯誤嗎? – RonU

回答

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); 
+0

工作。現在,當貸款中的任何值爲零或更少時,它應該拋出一個異常,但我在運行代碼時得到的所有信息如下:貸款信息:[email protected] 我在做什麼錯誤? – jshield

2

您需要首先使用「new」關鍵字創建貸款對象。這將調用構造函數。

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

要調用主方法中的構造函數,您需要使用new關鍵字。就像你在Loan構造函數中初始化loanDate一樣。

3

目前尚不清楚你想到這個什麼main做:

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

我懷疑你的意思是這是一個構造函數調用:

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

您的文章給出了一點點的指示可能導致此問題的術語混淆:

我想獲得貸款類calle d主要方法

你不要請致電一類。你調用一個構造函數或一個方法。你的意思是:

我想使main方法調用Loan類的構造函數。

在這一點上,它可能更清晰,你需要new

相關問題