如何使用compareto来比较字符串以获得按字母顺序排列的名称而不是分数?

c6ubokkw  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(261)

我必须使用给定的代码并对其进行修改,这样它就可以按名称的字母顺序返回输入的数据,而不是通过比较分数来返回结果。
这是压缩文件
下面是我运行golfapp2文件时的结果:

----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.

以下是我在高尔夫球手档案中更改的内容:

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

我不知道如何改变它,而不是。。。

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

…它会比较名字。

vojdkbi0

vojdkbi01#

你的代码无法通过编译,因为 this.name.compareTo(other.getName()) 不返回 boolean . 另一个错误是将名称与 this.name == other.name ,自 String s必须与 equals .
只需返回调用的结果 compareTo 两个名字(假设 name 财产永远不可能 null ) :

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

相关问题