0
private static String stringReverseRecursive(String str)
   {
       // saves the last letter of the word in the variable c
    char c = str.charAt (str.length()-1); 
       // take the last letter saved in c and joins the sub string of everything without the first letter and runs it again.
       return c + stringReverseRecursive((str.substring(0,str.length()-1))); 

   }

When I try to call the function then the compiler gives me an error saying that it goes out of range. I think there is something wrong with the lat line and the char c line.

TripWire
  • 532
  • 7
  • 18
Diya Saha
  • 21
  • 3
  • Hi, Recursive methods need a base case where if it's true the recursion ends... Otherwise it won't stop executing until an error such as the one you've described above happens or max stack depth is reached e.g. if (str.length() == 0) { return str; } If you're looking for more info on recursion, you can give this a read: http://tripwiretech.blogspot.co.nz/2014/09/the-recursion-checklist.html – TripWire Oct 25 '17 at 01:49
  • What happens if you reverse the empty string? Because your recursive call will always reduce to a call with the empty string, and if you don't handle that special case, your method doesn't work at all. – Erwin Bolwidt Oct 25 '17 at 01:49
  • @TripWire do you mean that I should put everything in the method in else – Diya Saha Oct 25 '17 at 01:52
  • Are you trying to _reverse_ a string, as the method name implies, or are you trying to find the _last letter_ of a string? – Tim Biegeleisen Oct 25 '17 at 01:59
  • You don't need a recursion for finding the last letter of a string. That's the last thing I would think of. – Naman Oct 25 '17 at 02:03
  • 1
    "the compiler gives me an error" no, it doesn't. What you're seeing is a *runtime error*. – Andy Turner Oct 25 '17 at 02:13

1 Answers1

1
private static String stringReverseRecursive(String str)
{ 
    if (str.isEmpty()) {

        return str;
    }

   // saves the last letter of the word in the variable c
   char c = str.charAt (str.length()-1); 
   // take the last letter saved in c and joins the sub string of everything without the first letter and runs it again.
   return c + stringReverseRecursive((str.substring(0,str.length()-1))); 

}

You want to check if the length is 0, to cater for an empty string e.g. ""

The if statement allows your code to complete execution and can be referred to as the base case.

TripWire
  • 532
  • 7
  • 18