0

I am creating a bankteller loop java code. I am trying to ask the user for what amount of money they would like to deposit into their account. I can get this to work once. For example, they will enter in $20 the first time. Then they will decide to put in $10 more. However, instead of displaying the current balance at $30, it only displays the one recently entered (the $10). How do I fix this?

Here is my code for that part of the loop in the menu that calls the class:

else if( userInput == 3 ){
            Account account = new Account();
            System.out.print("\nHow much would you like to deposit?: ");
            float money = input.nextFloat();
            account.deposit(money);
        }

Here is the code for deposit that is called:

public void deposit(float money) {
    if (money < 0) {
        System.err.println("Error: Can't deposit negative money.\n");
        return;
    }
    else {
        currentBalance = money + currentBalance;
        System.out.println("Current balance: $" + currentBalance + "\n");
    }
}
Joe
  • 31
  • 3
  • 5
    `Account account = new Account();` Don't create a new Account within the else if block. That variable is only visible within the block and no where else. Learn about variable scope. – Hovercraft Full Of Eels Sep 27 '17 at 02:55
  • Probably because it's creating a new `Account` instance every time, rather than reusing the instance. – Matt Ball Sep 27 '17 at 02:56
  • avoid `float. use `double` unless you really know you need a `float. However using a floating-point type for money is a very bad idea – phuclv Sep 27 '17 at 03:02

1 Answers1

0

You want to maintain the total balance so far. However, the moment you create a new Account object, balance gets initialized to zero and thus losing previous balance. What you need to do is create an Account object only once and then call deposit on the same Account object.

Sunil Singhal
  • 593
  • 3
  • 11