Frage

How do I add the deposit numbers? Do I need some kind of loop (I´m new to JAVA)?.

public class BankAccount {

    public static void main(String[] args) { 
        BankAccount account = new BankAccount();

        account.deposit(1000, "Deposit 1"); 
        account.deposit(2000, "Deposit 2");
        System.out.println("Balance: " + account.getBalance()); 
        account.deposit(3000, "Deposit 3"); 
        account.deposit(4000, "Deposit 4");
        System.out.println("Balance: " + account.getBalance());
    }

    private int currentBalance = 0;
private int getBalance() {

    int finalBalance = depositAmount + currentBalance;
    return finalBalance;
}

private int depositAmount;

public void deposit(int depositAmount) {

        this.depositAmount = depositAmount;
} 
}

Result should be:

Balance: 3000

Balance: 10000

War es hilfreich?

Lösung 2

Well, this might work for you

public class BankAccount {

  public static void main(String[] args) { 

      BankAccount account = new BankAccount();

      account.deposit(1000); 
      account.deposit(2000);
      System.out.println("Balance: " + account.getBalance()); 
      account.deposit(3000); 
      account.deposit(4000);
      System.out.println("Balance: " + account.getBalance());
  }

  private int currentBalance = 0;

  private int getBalance() {
      return this.currentBalance;
  }

  public void deposit(int depositAmount) {
      this.currentBalance = this.currentBalance + depositAmount;
  } 
}

Andere Tipps

Your deposit function is suspect. I think you want:

public void deposit(int depositAmount) {    
    this.currentBalance += depositAmount;
} 

Note the +=: this will accumulate the deposit amount. You should also get rid of the class member depositAmount which is also causing bugs. Your getBalance function then reduces to

private/*ToDo - this will probably be public eventually*/ int getBalance() {
    return currentBalance;
}

Two more issues though:

  1. This function deposit is not called directly since you are calling a version that also takes a string. (I'm assuming that the function you give is called eventually though).

  2. How will you model decimal values? Don't use a floating point as that will be imprecise. Use a currency type instead.

You are actually adding everything to the same object account . hence you are getting the result of all values inside it .(i.e) sum of all inputs 10000

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top