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);
		reverseWord += c;
		return reverseWord;

	public static void main(String args[]) {

		if (args.length != 1) {
			System.err.println("Usage: java TestReverse<word>");
9 Years
Discussion Span
Last Post by bobocqu

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);
[b]reverseWord += [/b]reverse(word.substring(1));
reverseWord += c;
Votes + Comments
Great help. Fixed my Problem. You have my thanks for identifying my oversight.
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.