Jack welch
Jack welch

Reputation: 1707

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;
}

Upvotes: 3

Views: 279

Answers (4)

Balaswamy Vaddeman
Balaswamy Vaddeman

Reputation: 8530

store that return value of method in totaltaxdue like below.

totaltaxdue += vassalandduke.calculateTaxDueByComponents();

Upvotes: 0

mcfinnigan
mcfinnigan

Reputation: 11638

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

Upvotes: 1

Shamim Hafiz - MSFT
Shamim Hafiz - MSFT

Reputation: 22094

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

vassalandduke.calculateTaxDueByComponents();

Change it to:

totaltaxdue += vassalandduke.calculateTaxDueByComponents();

Upvotes: 3

NPE
NPE

Reputation: 500357

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

vassalandduke.calculateTaxDueByComponents();

Change that to

totaltaxdue += vassalandduke.calculateTaxDueByComponents();

Upvotes: 7

Related Questions