954,536 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Recursion problem

I am writing a method (public static void reverse(String word)) that accepts a String as an argument, then returns the word in reverse order. The easy way would be to just have the recursive method print each letter but that wouldn't be my instructor. He wrote the main and the constructor for the method, its my job to just fill in the method body using recursion to solve this problem. The way he has it written, it appears to me that I have to break the word down, storing each character of the word into a character variable, then adding it to a new string variable in reverse order, however this is not working for me so well. I cannot seem to get the method to pass the value of the String reverseWord once it adds the last character to the next recursion as it works backwards through the characters. All I am getting is the first letter of the string when it does get to the println statement in the main. Here is my code. Thanks in advance for any help or ideas.

public class TestReverse {

public static String reverse(String word) {
String reverseWord = "";

if(word.length() == 0)
return "";

char c = word.charAt(0);
reverse(word.substring(1));
reverseWord += c;

return reverseWord;
}

public static void main(String args[]) {

if (args.length != 1) {
System.err.println("Usage: java TestReverse<word>");
System.exit(1);
}
System.out.println(reverse(args[0]));
}
}

Koldsoul
Light Poster
39 posts since Oct 2007
Reputation Points: 10
Solved Threads: 0
 

You have all the right logic, you're just missing half a line. Looks like a silly mistake on your part.

char c = word.charAt(0);
<strong>reverseWord += </strong>reverse(word.substring(1));
reverseWord += c;
destin
Junior Poster in Training
94 posts since Mar 2006
Reputation Points: 32
Solved Threads: 10
 

the guy above me was right. ^_^

bobocqu
Newbie Poster
12 posts since Nov 2008
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You