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

}
4

3 回答 3

4

将您的构造函数更改为

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

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

于 2016-08-25T04:13:57.053 回答
4

我相信问题出在您的构造函数中:

public BankAccount(double initBalance, double initInterest)
{
    balance = 0; // try balance = initBalance
    interest = 0; // try interest = initInterest
}
于 2016-08-25T04:14:12.200 回答
2

在构造函数中,默认情况下将余额和利息分配为 0,而不是分配方法参数。替换下面的代码

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

public BankAccount(double initBalance, double initInterest)
{
   this.balance = initBalance;
   this.interest = initInterest;
}
于 2016-08-25T04:23:00.643 回答