如何使用 compareTo 比较字符串以获得按字母顺序排列的名称而不是分数?
How to use compareTo to compare strings to get names in alphabetical order instead of scores?
我必须使用给定的代码并对其进行更改,这样就不会 return 通过比较分数来计算结果,它应该 return 按字母顺序按名称输入的数据。
这是ZIP FILE
这是我 运行 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.
这是我在 Golfer 文件中所做的更改:
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.compareTo(other.getName())
没有 return 和 boolean
。另一个错误是将名称与 this.name == other.name
进行比较,因为 String
s 必须与 equals
.
进行比较
只是return两个名字调用compareTo
的结果(假设name
属性永远不会是null
):
public int compareTo(Golfer other) {
return this.name.compareTo(other.getName());
}
我必须使用给定的代码并对其进行更改,这样就不会 return 通过比较分数来计算结果,它应该 return 按字母顺序按名称输入的数据。
这是ZIP FILE
这是我 运行 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.
这是我在 Golfer 文件中所做的更改:
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.compareTo(other.getName())
没有 return 和 boolean
。另一个错误是将名称与 this.name == other.name
进行比较,因为 String
s 必须与 equals
.
只是return两个名字调用compareTo
的结果(假设name
属性永远不会是null
):
public int compareTo(Golfer other) {
return this.name.compareTo(other.getName());
}