Recursion problem

Please support our Java advertiser: Programming Forums - DaniWeb Sister Site
Reply

Join Date: Oct 2007
Posts: 39
Reputation: Koldsoul is an unknown quantity at this point 
Solved Threads: 0
Koldsoul Koldsoul is offline Offline
Light Poster

Recursion problem

 
0
  #1
Nov 5th, 2008
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]));
	}
}
Reply With Quote Quick reply to this message  
Join Date: Mar 2006
Posts: 94
Reputation: destin is an unknown quantity at this point 
Solved Threads: 10
destin's Avatar
destin destin is offline Offline
Junior Poster in Training

Re: Recursion problem

 
1
  #2
Nov 5th, 2008
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);
reverseWord += reverse(word.substring(1));
reverseWord += c;
Reply With Quote Quick reply to this message  
Join Date: Nov 2008
Posts: 12
Reputation: bobocqu is an unknown quantity at this point 
Solved Threads: 0
bobocqu bobocqu is offline Offline
Newbie Poster

Re: Recursion problem

 
0
  #3
Nov 8th, 2008
the guy above me was right. ^_^
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:




Views: 1153 | Replies: 2
Thread Tools Search this Thread



Tag cloud for Java
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC