银行账户程序逻辑错误

时间:2016-08-25 04:10:48

标签: java account bank

我为家庭作业创建了一个非常基本的银行帐户计划,我不断收到逻辑错误。在存款,取款和增加利息之后,而不是计划给出总余额,而只是输出存入的金额 - 撤回。我很感激帮助,谢谢!

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
    }

}

3 个答案:

答案 0 :(得分:4)

将构造函数更改为

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

您没有将传递给构造函数的值赋给实例变量

答案 1 :(得分:4)

我认为问题出在你的构造函数中:

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

答案 2 :(得分:2)

在构造函数中,默认情况下,您将值分配为0表示余额和兴趣,而是分配方法参数。替换以下代码

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

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