Recursion in java
Hello, here's my problem. I must take a string and through recursion display it backwards. Here's what I have thus far...
Obviously I have something wrong because all I end up with is the string again. Any tips or hints on what I am doing wrong, or not doing?
public class StringFun
public static void main(String  args)
//Run Again feature
//Instantiate a keyboard reader
KeyboardReader r=new KeyboardReader();
string=r.readLine("Enter a string: ");
System.out.println( "The string '"+string+"' displayed in reverse shows '"+string(string, string.length())+"'");
//Run again option
runAgain=r.readChar("Run again (y/n)? ");
//Recursive method to display the string in reverse
static String string(String s, int pos)
if(pos>0) return s;
else return string(s, pos-1);
You should always analyze your algorithms on paper. If you would do this, then you'd see exactly what your function is doing. Use the word "dog" for example, you'd see that each call doesn't change the string at all and just decrements the position variable and all you return in the end is "dog". But this is assuming that you fixed your if statement, because if you look at that, pos is greater than zero on the first call from your main method and doesn't even get to the pseudo-recursive calls. You should look at an example of a recursive algorithm to get an idea on how they're constructed.
I'll give you a quick example of recursion and strings. This example is VERY close to the solution I came up with to create a reverse of a string.
Hope this gets you on the right track.
// This example takes the word and recursively shortens the word by taking
// out the first letter and appending that new word to the previous
// version of the string.
// Ex. word = wordordrdd, shane = shanehaneanenee
static String example(String s)
if s.length() > 1
return s + example(s.substring(1,s.length()-1))