Suppose you have a class StringTwo with just one instance va

Suppose you have a class StringTwo with just one instance variable private String word. Write public int compareTo( StringTwo o )word that performs the comparison between this and o in terms of the contents of the instance variable word. The value returned by the method is determined as follows:

-1 if either (a) this.word is shorter than than o.word or (b) they have the same length and this.word precedes o.word in the dictionary order;

+1 if either (a) this.word is longer than than o or (b) they have the same length and o.word precedes this.word in the dictionary order;

0 if the words are identical to each other.

Solution

public int compareTo(StringTwo o){
       if(this.word.length() < o.word.length() || (this.word.length() == o.word.length() && this.word.compareToIgnoreCase(o.word) < 0)) return -1;
       else if(this.word.length() > o.word.length() || (this.word.length() == o.word.length() && this.word.compareToIgnoreCase(o.word) > 0)) return 1;
       else return 0;
   }

Suppose you have a class StringTwo with just one instance variable private String word. Write public int compareTo( StringTwo o )word that performs the comparis

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site