2014-09-29 182 views
0

爲什麼jGrasp沒有意識到我的構造函數需要兩個雙打?特別是,因爲我只有一個構造函數。Java構造函數參數不匹配

這是我的課:

public class SavingsAccount{ 
    private double balance; 
    private double interestRate; 
    private double lastInterest; 

    public void SavingsAccount(double bal, double intRate){ 

     balance = bal; 
     interestRate = intRate; 
    } 

//Other methods 

} 

而在我的主要方法,我嘗試實例化它像這樣:

double bal = 500.00; 
double intRate = .002; 
SavingsAccount savings = new SavingsAccount(bal, intRate); 

但是當我嘗試運行,這是jGrasp,它讓我看到了錯誤,讀取

TestSavingsAccount.java:9: error: constructor SavingsAccount in class SavingsAccount cannot be applied to given types; 
    SavingsAccount savings = new SavingsAccount(bal, intRate); 
         ^
required: no arguments 
found: double,double 
reason: actual and formal argument lists differ in length 
1 error 

回答

3

您的「構造函數」有一個void字,使它成爲一種方法。構造函數不能有返回類型。您需要將其刪除:

public SavingsAccount(double bal, double intRate){ 

     balance = bal; 
     interestRate = intRate; 
    } 
2
 public void SavingsAccount(double bal, double intRate){ 
     balance = bal; 
     interestRate = intRate; 
    } 

應該是:

 public SavingsAccount(double bal, double intRate){ 
     balance = bal; 
     interestRate = intRate; 
    } 

你宣佈與添加無效的簽名的方法。