Can't get recursive function to work in Java

Posted by Ahmed Salah on Stack Overflow See other posts from Stack Overflow or by Ahmed Salah
Published on 2012-09-25T21:23:13Z Indexed on 2012/09/25 21:37 UTC
Read the original article Hit count: 308

Filed under:

I read docs about java recorsion and I thought I have understood it, but when I try to use it in the following example, it does not work as expected.

I a class account, which has amount and can have forther subAccount. I would have implemented one method getSum, which has to return the summ of the amount of the account and amount of all of its subaccount. In the following code, the call of the method getSumm() should return 550, but it behaves strange. can somebody help please?

public class Balance{
    ArrayList<Balance> subAccounts = new ArrayList<Balance>();
    String accountID = null;
    Double amount = null;
    double result=0;
    public double getSum(ArrayList<Balance> subAccounts){

        if(subAccounts !=null && subAccounts.size()>0){
            for (int i = 0; i < subAccounts.size(); i++) {

            result = result + getSum(subAccounts.get(i).subAccounts);

            }
        }
            else {
                return amount;
            }

        return result;
    }


    public static void main(String[] args) {
        Balance bs1 = new Balance();
        Balance bs2 = new Balance();
        Balance bs3 = new Balance();

        bs1.amount=100.0;
        bs2.amount=150.0;
        bs3.amount=300.0;
        ArrayList<Balance> subAccounts1 = new ArrayList<Balance>();

        bs2.subAccounts=null;
        bs3.subAccounts=null;
        subAccounts1.add(bs2);
        subAccounts1.add(bs3);
        bs1.subAccounts=subAccounts1;
        double sum= bs1.getSum(subAccounts1);
        System.out.println(sum);

}

}

© Stack Overflow or respective owner

Related posts about java