Siegfraud245 Siegfraud245 - 1 year ago 77
Java Question

Display a string backwards using recursion and substring method

I'm currently having trouble solving my code and its issue. I am trying to create a method that displays a string backwards with recursions and using substring. For Example if my I put "10 ten" as my argument, it should reverse word and repeat the letters 3 times.

it would show up like this:

Here is part of my method that focuses on that part.

public static String method3(Integer num,String line)
//base case
if (line.length() == 1)
//return line + line + line;
return line.substring(line.length()) + line.substring(line.length()) + line.substring(line.length());
//recursive case

return method3(num,line.substring(1)) + line.charAt(0) + line.charAt(0) + line.charAt(0);
}//end of else

My output is showing up this:


it's missing one more
"e" and 3 more "t"s at the end


This is my 2nd method that does "10 ten" repeats the words twice instead of thrice and not reverse

public static String method2(Integer num, String line)
//base case
if(line.length() == 1)
return line + line;

//recursive case
return line.substring(0,1) + line.substring(0,1)
+ method2(num,line.substring(1,line.length()));
}//end of else
}//end of method2


Answer Source

this is one way to do it:

private static String reverse(String string) {
    if(string.length() == 1)
        return string + string + string;

        return reverse(string.substring(1)) + string.charAt(0) + string.charAt(0) + string.charAt(0);