Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Suppose you have a class StringTwo with just one instance variable private Strin

ID: 3778854 • Letter: S

Question

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.

Explanation / Answer

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;
   }

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote