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);
}
}
Your logic was a little iffy.
The getSum shouldn’t take an argument because the subAccounts member variable is part of the object already.
Also you were collecting the internal sum in a member variable. Use local variables to avoid problems.
As everyone has everyone has already said… make sure you are not actually using recursion for this. This is simply a demonstration of how to use recusion so that is ok.
Here is the corrected program: