2014-03-27 16 views
0
有問題,爲什麼我收到錯誤無法找到我的簡單的投資類符號,這是一個編譯器錯誤

你好IM。錯誤不能簡單的投資類找到符號

public class Investments 
{ 
    //instance variables 
    private double moneyInvested; 
    private double investRate; 
    private int numOfYears; 

    //construscts a investment with the parameters moneyInvested, double investRate, int numOfYears 
    public Investments(double moneyInvested, double investRate, int numOfYears) 
    { 
     double amount = moneyInvested; 
     double rate = investRate; 
     int time = numOfYears; 
    } 

    public double ruleOf72() 
    { 
     return (72/rate); 
    } 

    public int simpleAnnual() 
    { 
     return Math.round(amount * Math.pow(1 + rate, time)); 
    } 

    public int compoundAnnual() 
    { 
     return Math.round(amount * Math.pow((1 +rate)^time)); 
    } 

} 
+1

費率,金額和時間必須在方法之外聲明 – Leo

回答

1

變量這裏聲明

double amount = moneyInvested; 
double rate = investRate; 
int time = numOfYears; 

都是local variables。他們不能在他們定義的塊之外訪問,即。在構造函數體外部。

您可能打算使用您的實例字段。

this.moneyInvested = moneyInvested; 
// ... etc. 

您應該重構代碼的其餘部分以使用這些實例變量。

0

嘗試這種方式

public class Investments { 
    // instance variables 
    private double moneyInvested; 
    private double investRate; 
    private int numOfYears; 

    double amount; 
    double rate; 
    int time; 

    public Investments(double moneyInvested, double investRate, int numOfYears) { 
     this.amount = moneyInvested; 
     this.rate = investRate; 
     this.time = numOfYears; 
    } 

    public double ruleOf72() { 
     return (72/this.rate); 
    } 

    public int simpleAnnual() { 
     return Math.round(this.amount * Math.pow(1 + this.rate, this.time)); 
    } 

    public int compoundAnnual() { 
     return Math.round(this.amount * Math.pow((1 + this.rate)^this.time)); 
    } 

} 
+0

仍然必須爲它做一個測試,但它似乎很好,謝謝! – user3466585

0

構造函數參數的名稱不必存在,因爲在你的類的局部變量。我可以使名字相同,但爲了清晰起見,我使用了內部名稱。

public class Investments 
{ 
    //instance variables 
    private double amount; 
    private double rate; 
    private int time; 

    //constructs an investment with the parameters moneyInvested, investRate, numOfYears 
    public Investments(double moneyInvested, double investRate, int numOfYears) 
    { 
     amount = moneyInvested; 
     rate = investRate; 
     time = numOfYears; 
    } 

    public double ruleOf72() 
    { 
     return (72/rate); 
    } 

    public int simpleAnnual() 
    { 
     return Math.round(amount * Math.pow(1 + rate, time)); 
    } 

    public int compoundAnnual() 
    { 
     return Math.round(amount * Math.pow((1 +rate)^time)); 
    } 

}