Mohmd Ali
Mohmd Ali

Reputation: 55

Method is re-initilizing my variable to 0

I currently have an accounts class having a Deposit method. Whenever I call this method, it re-initializes the totalamount to zero then it adds the amount added to it thus the total amount is always set to the added amount.

Accounts class:

public class Accounts {

double totalAmount;
public Accounts(){
    totalAmount = this.totalAmount;
}
 public double Deposit(double amountAdded) {
    totalAmount+=amountAdded;
    return totalAmount;
} 

Calling the method in the main:

System.out.println("Please enter the customer's account number you want to deposit money for");
int accountNumber = input.nextInt();
while(accountNumber == 0 || accountNumber < 0){
    System.out.println("Please enter an account number greater than 0");
 accountNumber = input.nextInt();
}
try{
for(int i = 0; i < index +1 ; i++){
    if(cust[i].accountNumber1 == accountNumber){
        System.out.println("Please enter the amount you want to deposit");
        double amount = input.nextDouble();
        acc[i] = new Accounts();
        double a = acc[i].Deposit(amount);
        System.out.println(a);
        break;
    }
}

let's say the current totalAmount for x person is 100. when calling the method Deposit with additional 300, the method will return 100 and not 400 as expected.

Upvotes: 0

Views: 56

Answers (1)

Marv
Marv

Reputation: 3557

You create a new Account instead of using the one from the array.

acc[i] = new Accounts();

This overwrites the account in the array and the newly created account has a balance of 0.

Upvotes: 1

Related Questions