I am making a program where i have to write a recursive function that reverses a string. I am a new programmer and need help. The function should return a String and take only one argument, also a String.

import java.io.*; 
public class RecursiveFunction {
    public static void main(String [] argv) throws IOException
    {
        BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in), 1);
        System.out.println("Enter a string that you would like to reverse");
        String userInput = stdin.readLine();
    }
    static String reverse(String userInput)
    {
        //what do i write here
        return userInput; 
    }
}

I don't know how to reverse the string or how to call the function from main().

Never mind I figured it out.

package recursivefunction;
import java.io.*; 
public class RecursiveFunction 
{
    public static void main(String [] argv) throws IOException
    {
        BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in), 1);
        System.out.println("Enter a string that you would like to reverse");
        String userInput = stdin.readLine();
        System.out.println(reverse.reverse(userInput));
    }
}
class reverse 
{
    public static String reverse(String s) 
    {
        int i, len = s.length();
        StringBuilder dest = new StringBuilder(len);
        for (i = (len - 1); i >= 0; i--)
        dest.append(s.charAt(i));
        return s; 
    } 
}

You need to read up on what a recursive function is. That isn't what you wrote/found/copied there.

I'm also wondering how closely you've looked at your outputs, given this particular line in your function

return s;

Ezzarel is correct on both points. I agree that I do not see a recursive function anywhere above.

Personally, this is where I would start:

import junit.framework.TestCase;

public class RecursiveFunctionTest extends TestCase {

	public void testReverseEmptyString() {
		assertEquals("", RecursiveFunction.reverse(""));
	}

	public void testReverseOneCharacterString() {
		assertEquals("x", RecursiveFunction.reverse("x"));
	}

	public void testReverseTwoCharacterString() {
		assertEquals("ba", RecursiveFunction.reverse("ab"));
	}

	public void testReverseThreeCharacterString() {
		assertEquals("321", RecursiveFunction.reverse("123"));
	}

}

To write a recursive function to reverse a string, I would consider the following points in this order:

  1. What is the correct result of reversing an empty string?
  2. What is the correct result of reversing a string of length one?
  3. If a string has more than one character, and I can separate the first character from the rest of the string, and I had some easy way to reverse the rest of the string, could I figure out how to use this to produce the desired result?

this will do the trick:

static String reverse(String userInput)
    {
        String temp = "";
        if(userInput.length() >= 1)
        {
            temp = userInput.substring(userInput.length()-1, userInput.length());
            temp += reverse(userInput.substring(0, userInput.length()-1));
        }
        return temp;
    }
commented: How does giving an OP code help him learn? -3

Need a little more explaining JeffGrigg. then how would this reverse a string that was inputted.

  1. Suppose I have a string "abc"...
  2. suppose I separate this into two strings: "a" and "bc".
  3. Suppose I call some other function that accepts "bc" and returns the correct reversed string, "cb".
  4. Now I have the two strings, "cb" and "a".
  5. I think that at this point I could form the correct result, "cba", and return it.

This kind of thinking is helpful for designing and writing recursive functions.

This is my assignment :
This function reverse() should return the reversed String to the caller, not print the reversed String itself.
Does this mean that it should not write the reversed string and just return it.
The java.lang.String member functions charAt() and substring() may be useful.

A recursive function will generally...

  1. Handle the simple cases. (like the empty string, and single character strings)
  2. Split the remaining problem into two parts, each of which is smaller and simpler than the original problem.
  3. Call itself (recursively) to solve one or both of the two smaller problems.
  4. Combine the results of solving the two smaller problems to get the correct result for the original problem.

(I did not mention printing in my previous post. I said "at this point"; I did not say "print." ;-)

Yes, the java.lang.String member functions charAt() and substring() will be useful.

juint isnt accepted in my program why?

juint isnt accepted in my program why?

If the line "import junit.framework.TestCase;" gives you an error like "The import junit cannot be resolved", then you are missing "junit.jar". In eclipse, right click on the project, select "Build Path -> Add Libraries...", select "JUnit" and press "Finish".

If you are using command line tools, the file "junit.jar" needs to be in the "class path." If you can't find the file, you can download it from http://junit.org/

Is this a recursive function

import java.io.*; 
public class CheckRecursiveFunction {
    public static void main(String [] argv) throws IOException
    {
        BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in), 1);// to use readLine();
        System.out.println("Enter a string that you would like to reverse");
        String userInput = stdin.readLine();// what the user inputs to be reversed.
        System.out.println(ReverseString.reverseIt(userInput));
    }
    static String reverse(String userInput)// created this for the recursion
    {
        String temp = "";// assigning no value so i could concatenate with another thing
        if(userInput.length() >= 1)
        {
            temp = userInput.substring(userInput.length()-1, userInput.length());
            temp += reverse(userInput.substring(0, userInput.length()-1));// cincatenate
        }
        return temp; // this will return the string but not print it.
    }
}
class ReverseString {
    public static String reverseIt(String s) {
        int i, len = s.length();
        StringBuffer dest = new StringBuffer(len);
        for (i = (len - 1); i >= 0; i--)
            dest.append(s.charAt(i));
        return dest.toString();
  }
}

Is this a recursive function
...

If you think it is a good solution for your homework assignment, as described by your instructor, then it is time to submit it to your instructor. You will receive a grade, and possibly other feedback.

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.