我正在尝试获取和比较存储在Player
中的List
对象的平均得分,其中每个对象都有一个first name
,last name
和一个列表scores
。例如({List
有一个对象):
[0] Firstname: "Michael", Lastname: "Morris", Scores: [88, 92]
我有一个在for循环内嵌套有for循环的代码,这给了我OutOfBounds
错误。我需要获得每个Player
的平均得分,并返回最高的Player
和最高的平均值。这是我目前的情况(命名有点客气):
public static PlayerScores findHighestScorer(List<PlayerScores> players) {
String team = players.toString();
PlayerScores thePlayers = new PlayerScores("", ""); // What to return
for (int i = 0; i < team.length() - 1; ++i) { // Get every player and their average score
PlayerScores player = players.get(i); // First player
int avg = player.getAverage();
for (int j = i + 1; j < team.length(); ++j) {
PlayerScores player2 = players.get(j); // FIXME: OutOfBoundsException Error
int avg2 = player2.getAverage();
if (avg2 < avg) {
thePlayers = player;
} else if (avg2 > avg) {
thePlayers = player2;
} else {
thePlayers = player;
}
}
}
return thePlayers;
任何和所有建议都将非常有帮助,谢谢!
答案 0 :(得分:1)
我希望这可以解决您的问题!干杯。
public static PlayerScores findHighestScorer(List<PlayerScores> players) {
PlayerScores bestScore = null;
// loop through list...
for (PlayerScores score : players) {
if (bestScore == null) {
bestScore = score;
} else {
if (bestScore.getAverage() < score.getAverage()) {
bestScore = score;
}
}
}
return bestScore;
}