-
Recusion Help
I am trying to use recursion to reverse a string. Here is what I have done so far. The problem is that java throws me an error saying that I am not returning a string. Any idea on what is happening?
public String reverse(String s){
if (start >= s.length()-1) {
String x=v.toString();
return x;
}
v.add(s.charAt(start));
start++;
reverse(s);
}
-
What variable is v? Put return anything after your reverse(s) call. It will either give you an unreachable code error or work how you intended it to.
The problem is if your condition doesn't fit the if statement then, regardless of having the recursive call, your program sees this as an incomplete method because nothing is returned.
-
Your method definition is this,
Code:
public String reverse(String s){
there is return a String. But where is the return statement in the method body?
-
I should confess,your imagination about recursion is so bad.I recommend to read some tutorials
Code:
public static String reverse (String s)
{
if (s.length() <= 1)
{
return s; // stopping case
}
else
{
return reverse(s.substring(1)) + s.charAt(0); // recursion
}
}
I don't understand where you got some variables,your stopping case is really awful,and of course you have no any return statement,OMG those are the base things.