# exercise of recursive method

Printable View

• 03-08-2008, 08:50 PM
amexudo
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!!
• 03-08-2008, 10:02 PM
hardwired
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.
• 03-09-2008, 06:55 PM
amexudo
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!