PDA

View Full Version : [Java] Recursion with strings


punx
01-05-2006, 02:38 AM
Hello once again I haveyet anohter question dealing with recursion. Heres my problem. I must take a string and through recursion display it backwards. Heres what I have thus far...

import TerminalIO.KeyboardReader;

public class StringFun
{
public static void main(String [] args)
{
//Variables
char runAgain='y';
String string;
//Run Again feature
while(runAgain=='y'||runAgain=='Y')
{
//Instantiate a keyboard reader
KeyboardReader r=new KeyboardReader();
//User input
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);
}
}

Obviously I have something wrong becuase all I end up with is the string again. Any tips or hints on what I am doing wrong, or not doing? Thanks.

-Chris

TheShaner
01-05-2006, 03:40 PM
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.

// 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))
else
return s
}
Hope this gets you on the right track.

-Shane

punx
01-05-2006, 04:12 PM
Thanks for the quick response. I'll go work with it. Thanks.

-Chris