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]));
	}
}

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;
commented: Great help. Fixed my Problem. You have my thanks for identifying my oversight. +2

the guy above me was right. ^_^

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.