Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call method recursively with java? [closed]

Tags:

java

recursion

There is java bean with list of elements and discount. I have to apply some calculate logic in those elements using recursion until that discount value gets zero.

Current implementation

for(CustomClass custom : customList) {
   Pair<CustomClass, Integer> returnVal = myMethod(custom, discount);
}

private Pair<CustomClass, Integer> myMethod(CustomClass custom, Integer discount) {
    pair.getKey().add(custom.setAmount(custom.getAmount - discount));
    pair.getValue().add(discount - custom.getAmount);
    return pair;
}

I have to do something like above and have to reuse the discount in multiple elements in the customList until it is zero. I want to make it recursive so that I get the discounted value in the CustomClass and discount is reduced. returnVal has updated discount but it is not being used in next iteration.

Could someone give me good approach to solve this issue.?

like image 895
Amit Avatar asked Nov 28 '25 01:11

Amit


1 Answers

To make recursive call, you need to call same method inside

private Pair<CustomClass, Integer> myMethod(CustomClass custom, Integer discount) {

    int dis = discount - custom.getAmount;
    pair.getKey().add(custom.setAmount(custom.getAmount - discount))
    pair.getValue().add(dis);

    if (dis <= 0)
    {
       return pair;
    }

    return myMethod (custom, dis);

}
like image 189
Ravi Avatar answered Nov 29 '25 15:11

Ravi