Results 1 to 4 of 4

Thread: Recusion Help

  1. #1
    calicocal is offline Member
    Join Date
    Nov 2008
    Posts
    13
    Rep Power
    0

    Default 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);
    }

  2. #2
    xcallmejudasx's Avatar
    xcallmejudasx is offline Senior Member
    Join Date
    Oct 2008
    Location
    Houston, TX & Flint, MI
    Posts
    609
    Rep Power
    7

    Default

    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.

  3. #3
    Eranga's Avatar
    Eranga is offline Moderator
    Join Date
    Jul 2007
    Location
    Colombo, Sri Lanka
    Posts
    11,372
    Blog Entries
    1
    Rep Power
    20

    Default

    Your method definition is this,

    Java Code:
    public String reverse(String s){
    there is return a String. But where is the return statement in the method body?

  4. #4
    serjant's Avatar
    serjant is offline Senior Member
    Join Date
    Jun 2008
    Location
    Ukraine,Zaporozhye
    Posts
    487
    Rep Power
    7

    Default

    I should confess,your imagination about recursion is so bad.I recommend to read some tutorials

    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
         }
       }
    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.
    Last edited by serjant; 12-02-2008 at 08:21 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •