2014-04-23 35 views
0

我試圖在計算貸款金額的類中創建方法。該方法應該返回「totalPay」,但它是說它沒有被聲明,你明白爲什麼?在同一類中的dif方法中訪問值

public loan(double anualInterestRate, int numberOfYears, double loanAmount){ 

    double base = (double) (loanAmount * (1+anualInterestRate/12)); 
    double exponent = (double) (numberOfYears * 12); 
    double totalPay = (double) Math.pow(base, exponent); 
} 

總付款方式未看到「totalPay」出於某種原因:

/** 
* 
* @return total payment 
*/ 
public double totalPayment(){ 
    return totalPay; 
} 

回答

2

你聲明的變量在構造使其可見僅在構造。不要這樣做。在課堂上聲明需要課堂可見度的課程。

class Loan { 
    private double base; 
    private double exponent; 
    private double totalPay; 

    public Loan(double anualInterestRate, int numberOfYears, double loanAmount){ 

     base = (double) (loanAmount * (1+anualInterestRate/12)); 
     xponent = (double) (numberOfYears * 12); 
     totalPay = (double) Math.pow(base, exponent); 

     // consider setting other fields with your parameters if they'll be 
     // needed elsewhere 
    } 
+0

我明白了!謝謝 :) – maribov