2017-02-23 74 views
1

我希望有人對我的帳戶類別和測試帳戶興趣類別提出專家意見。我面臨的問題是,來自測試帳戶興趣類的代碼僅在應該使用一次時才乘以前12個月的計算利息。帳戶和測試帳戶興趣類別

的問題是在

public double computeInterest(int n) 
     { 
      balance=balance*(Math.pow((1+rate),n/12)); 
      return balance; 
     } 

它是在哪裏的問題是,我不應該使用的平衡,但使用將存儲結果的變量這種方法,但我不明白的人這非常清楚,他只是聲明應該使用一個變量而非常模糊。

public class Account 
{ 
    private double balance; //STATE 
    private double interestRate; //STATE 
    private double rate;//STATE 

    public Account() 
    { 
     balance = 0; 
     interestRate = 0; 
    } 

    public Account(double amount, double interestRate) 
    { 
     balance = amount; 
     rate = interestRate; 

    } 

    public void deposit(double amount) 
    { 
     balance=balance+amount; 
    } 

    public void withdraw(double amount) 
    { 
     balance = balance - amount; 
    } 

    public void setInterest(double rate) 
    { 
     balance = balance + balance * rate; 
     //this.setInterst = setInterest; 
     //setInterest = InterestRate/12; 
    } 

    public double computeInterest(int n) 
    { 
     balance=balance*(Math.pow((1+rate),n/12)); 
     return balance; 
    } 

    public double getsetInterest() 
    { 
     return rate; 
    } 

    public double getBalance() 
    { 
     return balance; 
    } 

    public void close() 
    { 
     balance =0; 
    } 

} 

這是我的測試帳戶興趣班:

public class TestAccountInterest 
{ 
    public static void main (String[] args) 
    { 
     Account acc1 = new Account(100, 0.1);//0.10); 
     Account acc2 = new Account(133, 0.2); //0.20); 

     /************************************* 
     ACC1 ACCOUNT BELOW 
     *************************************/ 
     //acc1.deposit(100); 
     //acc1.withdraw(100); 
     System.out.println(acc1.computeInterest(12)); 
//  //acc1.computeInterest(12); 
//  System.out.println(acc1.computeInterest(24)); 

     /************************************** 
     ACC2 ACCOUNT BELOW 
     **************************************/ 
     acc2.withdraw(100); 
     acc2.deposit(100); 
     //acc2.computeInterest(24); 
     System.out.println(acc2.computeInterest(24)); 

    } 

} 

這是最後的輸出:

110.00000000000001 
191.51999999999998 

正如你可以看到第二個圖是由12乘以月份計算利息與24個月計算利息,這源於帳戶類別中的方法:

public double computeInterest(int n) 
     { 
      balance=balance*(Math.pow((1+rate),n/12)); 
      return balance; 
     } 

如果我拿出餘額仍然會導致錯誤,所以我對這個特定的部分感到困惑。

+2

'computeInterest'應該這樣做:計算利息。不更新*其他*狀態。或者返回餘額。它應該返回* interest *。 –

+0

它確實返回了(1 +利率)部分的利息,但我被告知第一部分餘額應該被移除 – Omor

+0

它不*返回利息。它返回餘額。 *設置*平衡,這是違反直覺的。 –

回答

0

代碼,

public double computeInterest(int n) { 
    balance = balance * (Math.pow((1 + rate), n/12)); 
    return balance; 
} 

應改爲

public double computeInterest(int n) { 
    return balance * Math.pow(1 + rate, n/12); 
} 

在計算利息,不應更改balance場。您可能希望有一個單獨的方法來更新balance,您可以更新balance = balance + computed_interest或類似的東西。

此外,我刪除了不必要的括號。這不是一個錯誤,而只是讓你的代碼不易讀。

+0

我重新格式化了您的代碼以使其易讀。 –