Results 1 to 3 of 3
Thread: exercise of recursive method
- 03-08-2008, 07:50 PM #1
Member
- Join Date
- Mar 2008
- Posts
- 2
- Rep Power
- 0
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, 09:02 PM #2
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, 05:55 PM #3
Member
- Join Date
- Mar 2008
- Posts
- 2
- Rep Power
- 0
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
-
Recursive Method ==> find minimum value from array
By NatNat in forum New To JavaReplies: 1Last Post: 02-16-2008, 09:10 PM -
Recursive Method ==> find how many times a value is repeated in an array
By NatNat in forum New To JavaReplies: 2Last Post: 02-16-2008, 08:52 PM -
Recursive Method
By bluegreen7hi in forum New To JavaReplies: 5Last Post: 11-29-2007, 04:45 AM -
I/O exercise
By Feldom in forum New To JavaReplies: 1Last Post: 10-28-2007, 04:48 PM -
help with exercise
By e_as're in forum New To JavaReplies: 3Last Post: 09-25-2007, 10:14 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks