简体   繁体   中英

Recursive method

I have an array list that could contain component or composite and each component or composite has a tax field that i would like to get the value.The purpose of this method is to get the total tax due by all the components and composites in the array list.A component can also contain a composite .The problem is when a component contains a composite ,My method does not get the value in the composite

ArrayList allprinceSubjects = new ArrayList();
public double calculateTaxDueByComponents(){
    double totaltaxdue=0;
    Iterator iterator = vassalsanddukes.iterator();
    while(iterator.hasNext()){
        RiruritaniaSubjects vassalandduke=(RiruritaniaSubjects) iterator.next();
        totaltaxdue+=vassalandduke.getTaxDue();
        vassalandduke.calculateTaxDueByComponents();


    }
    return totaltaxdue;
}

The problem is that you when you call calculateTaxDueByComponents() recursively, you discard the result:

vassalandduke.calculateTaxDueByComponents();

Change that to

totaltaxdue += vassalandduke.calculateTaxDueByComponents();

Not sure how your business logic are implemented, but I think the following line needs changing:

vassalandduke.calculateTaxDueByComponents();

Change it to:

totaltaxdue += vassalandduke.calculateTaxDueByComponents();

you're not assigning the value of vassalandduke.calculateTaxDueByComponents(); to anything - you should most likely be adding it to totaltaxdue, not so?

在totaltaxdue中返回方法的值,如下所示。

totaltaxdue += vassalandduke.calculateTaxDueByComponents();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM