【问题标题】:Bank Account Program Logic Error银行账户程序逻辑错误
【发布时间】:2016-08-25 04:10:47
【问题描述】:

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

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
    }

}

【问题讨论】:

  • 您没有正确初始化变量。你应该有balance=initBalance ; interest=initInterest
  • 没有解释的否决票是没有帮助的。他们还可以阻止新用户询问和寻求帮助或建议。我认为应该尽可能避免新用户的否决投票问题。对于那些我建议相反的人:解释而不投反对票。

标签: java account bank


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    将你的构造函数更改为

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

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 2016-11-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-22
        • 1970-01-01
        • 2014-08-27
        • 2015-09-08
        • 1970-01-01
        相关资源
        最近更新 更多