我阅读了有关 java recorsion 的文档,我以为我已经理解了,但是当我尝试在以下示例中使用它时,它无法按预期工作。
我是一个类account
,它有amount
并且可以有其他子帐户。我会实现一种方法getSum
,它必须返回账户金额和所有子账户金额的总和。在下面的代码中,该方法的调用getSumm()
应该返回 550,但它的行为很奇怪。有人可以帮忙吗?
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);
}
}