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
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