• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

Compare() - from Master Exam

 
Ranch Hand
Posts: 664
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This is from MasterExam

I am not sure what is going on in the Compare Method.
How is it doing the comparision.




The answer is good
 
Ranch Hand
Posts: 247
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
public int compare(String s1,String s2)
{
return s2.charAt(1)-s1.charAt(1);
}

In the code above, say s1="cat", and s2="dog".
The s2.charAt(1) = 'a' and s1.charAt(1)='o'.
Therefore compare() will return the int value of 'o'-'a'.

Note that compare() does not account for when s1 or s2 or both have length 1 or 0. It should have code to take care of these situations and also when either or both of them are null.
 
victor kamat
Ranch Hand
Posts: 247
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I meant to say s1.charAt(1) = 'a' and s2.charAt(1) ='o'
 
Nabila Mohammad
Ranch Hand
Posts: 664
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
So that means its comparing the three words in (reverse of )Alphabetical order based on the second letter as its
s2.charAt(1) -s1.charAt(1)
and not
s1.charAt(1) -s2.charAt(1).

Right?
 
victor kamat
Ranch Hand
Posts: 247
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Right
 
Nabila Mohammad
Ranch Hand
Posts: 664
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
THanks
reply
    Bookmark Topic Watch Topic
  • New Topic