Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate strings using recursion

Tags:

java

recursion

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 ));
}
like image 799
Keith Bryant Avatar asked Oct 26 '25 22:10

Keith Bryant


1 Answers

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 "";
}   
like image 169
nhouser9 Avatar answered Oct 28 '25 15:10

nhouser9