2016-08-25 105 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; 
}