Results 1 to 4 of 4
Thread: Recusion Help
- 12-01-2008, 06:55 PM #1
Member
- Join Date
- Nov 2008
- Posts
- 13
- Rep Power
- 0
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);
}
- 12-01-2008, 08:08 PM #2
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.
- 12-02-2008, 08:10 AM #3
- Join Date
- Jul 2007
- Location
- Colombo, Sri Lanka
- Posts
- 11,374
- Blog Entries
- 1
- Rep Power
- 18
Your method definition is this,
there is return a String. But where is the return statement in the method body?Java Code:public String reverse(String s){
- 12-02-2008, 08:18 AM #4
I should confess,your imagination about recursion is so bad.I recommend to read some tutorials
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.Java 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 } }Last edited by serjant; 12-02-2008 at 08:21 AM.


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks