银行账户程序逻辑错误

Bank Account Program Logic Error

我为家庭作业创建了一个非常基本的银行账户程序,但我不断收到逻辑错误。在存款、取款和增加利息后,程序不会给出总余额,而只是输出存款金额 - withdrawn.I 感谢帮助,谢谢!

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;
}

测试Class

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
    }

}

将构造函数更改为

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

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

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

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

在构造函数中,您默认将余额和利息的值指定为 0,而不是指定方法参数。替换下面的代码

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

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