Search code examples
javabinary-search-treecompareto

How to use compareTo to compare strings to get names in alphabetical order instead of scores?


I have to use the given codes and alter it so that instead of returning results by comparing scores, it should return the data input by the names in alphabetical order.

Here is the ZIP FILE

Here are my results when I run the GolfApp2 file:

 ----jGRASP exec: java GolfApp2

Golfer name (press Enter to end): Annika
Score: 72
Golfer name (press Enter to end): Grace
Score: 75
Golfer name (press Enter to end): Arnold
Score: 68
Golfer name (press Enter to end): Vijay
Score: 72
Golfer name (press Enter to end): Christie
Score: 70
Golfer name (press Enter to end): 

The final results are
68: Arnold
70: Christie
72: Vijay
72: Annika
75: Grace

 ----jGRASP: operation complete.

Here's what I have changed in the Golfer file:

 public int compareTo(Golfer other)
   {
      if (this.name.compareTo(other.getName()))
         return -1;
      else 
         if (this.name == other.name)
            return 0;
         else 
            return +1;
   }

I am confused on how to change it so that instead of...

public int compareTo(Golfer other)
  {
    if (this.score < other.score)
      return -1;
    else 
      if (this.score == other.score)
        return 0;
      else 
        return +1;
  }

...it would compare the names.


Solution

  • Your code wouldn't pass compilation, since this.name.compareTo(other.getName()) doesn't return a boolean. Another error is comparing the names with this.name == other.name, since Strings must be compared with equals.

    Simply return the result of calling compareTo for the two names (assuming the name property can never be null) :

    public int compareTo(Golfer other) {
        return this.name.compareTo(other.getName());
    }