Results 1 to 2 of 2
Thread: Recursion in java
- 07-22-2007, 10:13 PM #1
Member
- Join Date
- Jul 2007
- Posts
- 40
- Rep Power
- 0
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?Java Code: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); } }
Thanks.
- 08-07-2007, 06:23 AM #2
Member
- Join Date
- Jul 2007
- Posts
- 40
- Rep Power
- 0
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.Java Code:// 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 }
Similar Threads
-
Help With Recursion
By andrew777 in forum New To JavaReplies: 1Last Post: 03-29-2008, 12:51 PM -
recursion
By kdeighan in forum New To JavaReplies: 3Last Post: 01-25-2008, 09:48 PM -
Recursion
By bozovilla in forum Advanced JavaReplies: 3Last Post: 01-07-2008, 04:53 PM -
recursion
By ravian in forum New To JavaReplies: 2Last Post: 12-03-2007, 05:15 PM -
Help with recursion
By scts102 in forum New To JavaReplies: 1Last Post: 11-19-2007, 10:07 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks