Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/389.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何使用compareTo来比较字符串,以获得按字母顺序排列的名称,而不是分数?_Java_Binary Search Tree_Compareto - Fatal编程技术网

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

Java 如何使用compareTo来比较字符串,以获得按字母顺序排列的名称,而不是分数?,java,binary-search-tree,compareto,Java,Binary Search Tree,Compareto,我必须使用给定的代码并对其进行修改,这样它就可以返回按姓名字母顺序输入的数据,而不是通过比较分数来返回结果 这是你的电话号码 以下是我运行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

我必须使用给定的代码并对其进行修改,这样它就可以返回按姓名字母顺序输入的数据,而不是通过比较分数来返回结果

这是你的电话号码

以下是我运行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;
  }

…它将比较名称。

您的代码不会通过编译,因为this.name.compareTother.getName不会返回布尔值。另一个错误是将名称与this.name==other.name进行比较,因为字符串必须与equals进行比较

只需返回为两个名称调用compareTo的结果,假设name属性永远不能为null:

this.name==other.name是按值比较字符串的一种非常糟糕的方法。改为使用.equals。最好直接使用this.name.compareTother.name。
public int compareTo(Golfer other) {
    return this.name.compareTo(other.getName());
}