Jessica Fan Jessica Fan -4 years ago 207
Java Question

How to write a recursive string method that takes in int?

I need to write a recursive method called String song (int n).
Say I have a sentence: I have n candy, you take one out, pass it around, n-1 left.

I have n-1 candy, you take one out, pass it around, n-2 left.

and it goes on and stops when n = 0.

How do I put this string inside the song method? If I do: return "I have "+ n + " candy, you take one out...."
It doesn't compile. How do I return both the int and the string together?

Thank you so much!

Answer Source

If I do: return "I have "+ n + " candy, you take one out...." It doesn't compile

It should compile. At least does for me.

public String song(int n) {
    return "I have "+ n + " candy, you take one out....";
}

But that isn't recursive at all; the function doesn't call itself.

How do I put this string inside the song method?

What string? The candy name? Why not a parameter?

public String song(String candy, int n) {
    return "I have "+ n + " " + candy + ", you take one out....";
}

Should still compile.

How do I return both the int and the string together?

If you've learned Java, you can't. Methods only have one return type. You could print the string, not return the whole song...

Really, though, you don't need to return the integer.

You need to call the function recursively, right?

So, you can do that like this

public String song(int n) {
    return "I have " + n + "candy.\n" + song(n-1);
}  

But that will cause a StackOverflowError, so good luck coding the rest!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download