Java Recursive functions, single initialization of value

I want to use a recursive function to achieve some stuff, which includes printing output. I want to give increasing levels of tab in the output being printed. I was able to successfully achieve this using the following methodology

int count =0;
public void m1 (Object n)
{
    count++;
    List nl = n.getChildren();
    int nlsize = nl.size();
    for (int i = 0 ; i < nlsize ; i++)
    {
        String objName = nl.getObjAt(i).getText();
        for (int tab=0; tab<count ; tab++) {System.out.print("\t");}
        System.out.println(objName);
        m1(nl.getObjAt(i));
    }
    count--;
}

But the limitations and problems of this approach, what with the initialization of count outside, are pretty obvious.

Is there some way to achieve this? I know java doesn't accept default values for parameters being passed, or else that could be a possible solution. How else can this be achieved?

Jon Skeet
people
quotationmark

I would split it into two methods: one public one with just the "natural" parameters, and one private one with two parameters (in this case n and count), passing in the initial value. You won't need to modify count within the method - just pass count + 1 in the recursive call:

public void m1(Object n) {
    m1(n, 0);
}

private void m1(Object n, int count) {
    List nl = n.getChildren();
    int nlsize = nl.size();
    for (int i = 0; i < nlsize; i++) {
        String objName = nl.getObjAt(i).getText();
        for (int tab = 0; tab < count; tab++) {
            System.out.print("\t");
        }
        System.out.println(objName);
        m1(nl.getObjAt(i), count + 1);
    }
}

Note that this starts off with no tabs at the outermost level, whereas your original code used one tab. You can just pass 1 instead of 0 if you want.

(I would also rename just about everything there. Names are very important - spend some time picking good ones!)

people

See more on this question at Stackoverflow