Results 1 to 3 of 3
  1. #1
    amexudo is offline Member
    Join Date
    Mar 2008
    Posts
    2
    Rep Power
    0

    Default exercise of recursive method

    hello,
    i was trying to do an exercise but i cannot resolve it.
    the exercise asks us to write a recursive method
    public static int myCompare (String s1, String s2)
    that receives 2 strings and compare them.
    it returns 1 if string s1 comes after s2 in the dictionary (lexicographly)
    the method returns 2 if string s1 comes after s2 in the dictionary
    and it returns 0 if strings s1 and s2 are exactly the same.
    example:
    input:
    s1 = "mother" and s2 = "class"
    output: 1 ('m' comes after 'c')

    the method must be a recursive method and mustn't use loops.

    in the solution it's only allowed to use the following existing methods (from String class):
    public char charAt(int i)
    public String substring(int i)
    public int length()

    thanks for your help!!

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

    Default

    To get you started think about comparing the charAt(0) of each string. If they are the same you remove the first letter from each string and return a call to the method using the substrings as arguments.

  3. #3
    amexudo is offline Member
    Join Date
    Mar 2008
    Posts
    2
    Rep Power
    0

    Default code

    public static int myCompare(String s1, String s2){

    if (s1.charAt(0)==s2.charAt(0)){
    if (s1.length() == 1 && s2.length()!= 1)
    return 2;
    else
    if (s1.length() != 1 && s2.length() ==1)
    return 1;
    else
    if (s1.length()==1 && s2.length() == 1)
    return 0;
    else
    return myCompare(s1.substring(1),s2.substring(1));
    }
    else {
    if (s1.charAt(0)<s2.charAt(0))
    return 2;
    else
    return 1;
    }
    }



    this is what i've done. i think it's right, didn't find any problem till now.
    thanks again for your help!

Similar Threads

  1. Replies: 1
    Last Post: 02-16-2008, 10:10 PM
  2. Replies: 2
    Last Post: 02-16-2008, 09:52 PM
  3. Recursive Method
    By bluegreen7hi in forum New To Java
    Replies: 5
    Last Post: 11-29-2007, 05:45 AM
  4. I/O exercise
    By Feldom in forum New To Java
    Replies: 1
    Last Post: 10-28-2007, 05:48 PM
  5. help with exercise
    By e_as're in forum New To Java
    Replies: 3
    Last Post: 09-25-2007, 10:14 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
  •