2016-08-25 102 views
-2

我創建了一個非常基本的銀行賬戶程序作業,我不斷收到邏輯錯誤。取而代之的是,在存款,提款和增加利息之後提供總餘額的計劃,只是輸出存入的金額 - 撤回。我很感激幫助,謝謝!銀行賬戶程序邏輯錯誤

public class BankAccount 
{ 

    public BankAccount(double initBalance, double initInterest) 
    { 
     balance = 0; 
     interest = 0; 
    } 

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

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

    public void addInterest() 
    { 
     balance = balance + balance * interest; 
    } 

    public double checkBal() 
    { 
     return balance; 
    } 

    private double balance; 
    private double interest; 
} 

測試類

public class BankTester 
{ 

    public static void main(String[] args) 
    { 
     BankAccount account1 = new BankAccount(500, .01); 
     account1.deposit(100); 
     account1.withdraw(50); 
     account1.addInterest(); 
     System.out.println(account1.checkBal()); 
     //Outputs 50 instead of 555.5 
    } 

} 
+1

您沒有正確初始化您的變量。你應該有'balance = initBalance;利息= initInterest'。 –

+1

沒有解釋的倒票沒有幫助。他們也可以阻止新用戶詢問並尋求幫助或建議。 I 認爲應該儘可能地避免新用戶的投票問題。對於那些我推薦相反的人:解釋沒有投票。 – c0der

回答

4

我相信問題出在你的構造函數上:

public BankAccount(double initBalance, double initInterest) 
{ 
    balance = 0; // try balance = initBalance 
    interest = 0; // try interest = initInterest 
} 
4

更改您的構造函數

public BankAccount(double initBalance, double initInterest) 
    { 
     balance = initBalance; 
     interest = initInterest; 
    } 

你沒有指定要傳遞到構造函數實例變量的值

2

在構造函數中,默認情況下將值分配爲0來表示餘額和興趣,而不是分配方法參數。替換下面的代碼

public BankAccount(double initBalance, double initInterest) 
{ 
    balance = 0; 
    interest = 0; 
} 

public BankAccount(double initBalance, double initInterest) 
{ 
    this.balance = initBalance; 
    this.interest = initInterest; 
}