Results 1 to 3 of 3
  1. #1
    cachi is offline Member
    Join Date
    Jul 2007
    Posts
    40
    Rep Power
    0

    Default Help with recursive function in java

    Hi, how would i take
    Java Code:
    public String reversal(String x){
    int y = x.lenght();
    String s =""
    for(Int j=y-1;j>=0;j--)
      s+=x.charAt(j);
    return s;
    }
    and write a recursive function for it to do the same thing?
    Thanks

  2. #2
    brianhks is offline Senior Member
    Join Date
    Jul 2007
    Posts
    135
    Rep Power
    0

    Default

    this smells like a homework problem to me ;)

  3. #3
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    8

    Default

    Java Code:
    public class RecursionTest {
        public static void main(String[] args) {
            String s = "Hello World";
            int len = s.length();
            System.out.println("reversal("+s+") = " + reversal(s));
            System.out.println("move("+s + ", "+len+") = " + move(s, len));
        }
    
        public static String reversal(String x){
            int y = x.length();
            String s ="";
            for(int j = y-1; j >= 0; j--)
                s+=x.charAt(j);
            return s;
        }
    
        private static String move(String s, int n) {
            if(n < 1)
                return s;
            char c = s.charAt(0);
            s = s.substring(1, n) + String.valueOf(c) +
                s.substring(n);
            //System.out.printf("s(1, &#37;d) =  %s  c = %s  s(%d) = %s%n",
            //                   n, s.substring(1, n),
            //                   String.valueOf(c),
            //                   n, s.substring(n));
            return move(s, n-1);
        }
    }

Similar Threads

  1. How to use a function in java
    By olikhvar in forum New To Java
    Replies: 2
    Last Post: 02-16-2008, 02:57 AM
  2. Use Perl function with java
    By lenny in forum Advanced Java
    Replies: 1
    Last Post: 08-07-2007, 06:25 AM
  3. Recursive Anagram
    By zoe in forum Advanced Java
    Replies: 1
    Last Post: 08-07-2007, 06:15 AM
  4. Help with recursive implementation
    By toby in forum Advanced Java
    Replies: 1
    Last Post: 08-07-2007, 05:57 AM
  5. Php explode function, equivalent java
    By fernando in forum Advanced Java
    Replies: 1
    Last Post: 07-31-2007, 05:44 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
  •