-2

I create a very basic bank account program for homework and I keep getting a logic error. Instead of the program giving the total balance after the depositing, withdrawing, and adding interest it just outputs the amount deposited - withdrawn.I appreciate the help, thanks!

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

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

}
Travis Rodman
  • 607
  • 1
  • 6
  • 14
DavidGilly
  • 47
  • 8
  • 1
    You are not initializing your variables correctly. You should have `balance=initBalance ; interest=initInterest`. – Ryan B. Aug 25 '16 at 04:16
  • 1
    Down-votes with no explanations are not helpful. They can also discourage new users asking and seeking help or advice. I think that down voting question of new users should be avoided as much as possible. For those I recommend the opposite : explanation without down-voting. – c0der Aug 25 '16 at 04:23

3 Answers3

4

Change your constructor as

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

You are not assigning the value you are passing to the constructor to the instance variables

Thiyagu
  • 17,362
  • 5
  • 42
  • 79
4

I believe the problem is in your constructor:

public BankAccount(double initBalance, double initInterest)
{
    balance = 0; // try balance = initBalance
    interest = 0; // try interest = initInterest
}
Zay Lau
  • 1,856
  • 1
  • 10
  • 17
2

In the constructor you are by default assigning the values as 0 for balance and interest, instead assign the method parameters. Replace the below code

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

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