This has been giving me a headache all day and I cannot figure it out. The goal is to have the string repeat itself using the times param as the number of times the string is able to repeat its self. for example:
stringTimes("Hello", 3); //should return HelloHelloHello,
stringTimes("cat", 2); //should return catcat,
stringTimes("monkey", 0); //should return _____,
below is the code I've been using and I'm getting nothing. HELP!!!
public static String stringTimes(String theString, int times)
{
String adder = "";
if (times >= 1) {
adder += theString;
return stringTimes(theString, times - 1);
}
return adder;
}
public static void main(String[] args) {
System.out.println(stringTimes("hello ", 8 ));
}
Your method is going down to the last recursive call and then just returning an empty string. Change it to:
public static String stringTimes(String theString, int times)
{
if (times >= 1) {
return theString + stringTimes(theString, times - 1);
}
return "";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With