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