I am trying an example from my CS class. We learned recursion recently, and one of the examples I was given was to reverse a given string. The Java program compiles correctly, but when it is actually executed, instead of getting the intended result, I get this as my outcome.
at RevString.reverse(RevString.java:16)
This repeats itself until the program ends.
Here is the source code.
//demonstrate recursion by reversing a string of characters
public class RevString
{
public static void main(String[] args)
{
String s= "abcd";// the given string
System.out.println(reverse(s));//shows the result of reversing the string
}
/*
//The reverse method takes a string variable as a parameter.
//It then takes the first character of a string and
//attaches it to the end of the string.
*/
public static String reverse(String s)
{
if(s.length()==1)
return s; //returns the original string only if it is one character
else
reverse(s.substring(1) + s.charAt(0));//calls the reverse method to take the first character and reverse it
return s;
}
}
What am I doing wrong?