所以我需要一个班级HighscoreEntry
来保存一个玩家名字和他们的分数。在另一个班级HighscoreTable
中,我必须列出队员的名字和分数,并将分数从最高到最低排序。如何才能获得整数分数?
public class HighscoreEntry {
private String name;
private int score;
public HighscoreEntry(String name, int score){
this.name=name;
this.score=score;
}
public int getScore(){
return this.score;
}
public String toString(){
return "Player: "+this.name+", score: "+this.score;
}
}
所以我的“入门代码”:
public class HighscoreTable {
private HighscoreEntry [] player;
public HighscoreTable(HighscoreEntry [] p){
player = new HighscoreEntry[p.length];
for(int i=0;i<p.length;i++){
player[i]=p[i];
if (player.getScore()[i]>player.getScore()[i+1]){
// i wanted here to sort out the score only but it doesn't work with getScore()
}
}
}
}
答案 0 :(得分:3)
您正在错误地访问该阵列。你不能在数组上调用非数组方法。
if (player.getScore()[i]>player.getScore()[i+1])
变量player
是一个数组,因此您无法在其上调用getScore
。您必须先使用player[i]
访问该对象,然后调用此方法
player[i].getScore();
答案 1 :(得分:0)
您无法像这样访问数组索引。
player.getScore()[i]>player.getScore()[i+1]
需要成为
player[i].getScore() > player[i+1].getScore()
如果没有条件检查你是否在最后一个索引,我也不会去访问这样的索引。
player[i+1].getScore()
可能导致越界异常。
答案 2 :(得分:0)
正如Murat K.在他的回答中所述,你以错误的方式访问数组。但是你的排序算法无论如何都行不通。虽然实现一个算法来排序数组相当容易,但我建议使用“默认”方式在Java中使用Collection Framework:
不是将HighscoreEntry
保存在数组中,而是将它们存储在列表中,例如一个ArrayList。然后让HighscoreEntry
实施Comparable。 HighscoreEntry
的代码如下所示:
public class HighscoreEntry implements Comparable<HighscoreEntry> {
private int score;
public int compareTo(HighscoreEntry he) {
return score - he.score;
}
[other code]
}
然后,您可以对条目进行排序,如:
List<HighscoreEntry> list = Arrays.asList(player);
Collections.sort(list);