1

I have to write a recursive toString method for an array of objects. I understand how recursion works I've done other recursive methods correctly in the same program I'm just lost on this one method. The output for this method is blank. Also there is another non-recursive toString() in another class that converts one House object to String.

    public String toString(House[] list, int n)
{
    if (n == 0)
        return "";
    else
    {
        toString(list, n-1);
        return toString(list, n-1);
    }
}
itsJL3
  • 11
  • 1

1 Answers1

2

You need to accumulate each element before going to the next call:

public static String toString(String[] array, int n)
{
    if (n == 0) return "";
    else
    {
        return array[array.length - n] + toString(array, n-1);
    }
}
System.out.println(toString(new String[]{"abc", "def", "ghi"}, 3));

Output:

abcdefghi

Here is another snippet that adds separator in between the elements:

public static String toString(String[] array, int n)
{
    if (n == 0) return "";
    else
    {
        return array[array.length - n] + (n > 1 ? ", " : "") + toString(array, n-1);
    }
}

Output:

abc, def, ghi
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
  • Ok I got to print cycle through properly except instead of printing the House objects it's printing seven nulls, (there are seven houses in the array of house objects) why would it print null for the houses instead of the actual information? – itsJL3 Mar 03 '20 at 04:05
  • @itsJL3 Most likely you did not initialize them. See: https://stackoverflow.com/questions/1922677/nullpointerexception-when-creating-an-array-of-objects – Eng.Fouad Mar 03 '20 at 04:09