Search code examples
javarecursionlocaldate

Java method Recursion is giving problem once the value is derived


I have a program which should derive the date. I am passing set of holidays and the input date. If my input date is within the holiday set, then I am adding one day to it. Again I am checking that new date is in the holiday set or not..etc. Once the new derived and the new date is not in the list of holiday set, it has to return from that method. But, instead of that method is calling again and my derived date is adjusting back. I am not understanding where I am going wrong. I am unable to pass any counter-argument to my method to run based on a counter. This is my code.

package com.pamu.test;

import java.time.LocalDate;
import java.util.TreeSet;

public class ReturnCheck {

    private LocalDate determineNextWorkingDayIfHolidayOrWeekend(TreeSet<LocalDate> holidaysSet, LocalDate date) {
        System.out.println("determineNextWorkingDayIfHolidayOrWeekend");
        if (holidaysSet.contains(date)) {
            System.out.println(date+" : is a holiday");
            System.out.println("Adding "+1+" day to "+date);
            date = date.plusDays(1);
            System.out.println("So, new date is "+date);
            this.determineNextWorkingDayIfHolidayOrWeekend(holidaysSet, date);
        }
        return date;
    }

    public static void main(String args[]) {
        TreeSet<LocalDate> holidaysSet = new TreeSet<LocalDate>();
        holidaysSet.add(LocalDate.parse("2019-04-30".substring(0, 10)));
        holidaysSet.add(LocalDate.parse("2019-05-01".substring(0, 10)));
        LocalDate date = LocalDate.parse("2019-04-30".substring(0, 10));
        ReturnCheck tdc = new ReturnCheck();
        LocalDate derived = tdc.determineNextWorkingDayIfHolidayOrWeekend(holidaysSet,date);
        System.out.println(derived);
    }
}

Any help is highly appreciated.


Solution

  • You need to eventually use the result of your recursion by changing the line

    this.determineNextWorkingDayIfHolidayOrWeekend(holidaysSet, date);
    

    inside the inner-most if to

    return this.determineNextWorkingDayIfHolidayOrWeekend(holidaysSet, date);
    

    which then outputs

    2019-05-02