我试图运行一个for循环,在数组列表中打印每个用户分数。 但我不知道如何输出最高/最高分的人。有人可以帮助我吗?
for (int i = 0; i < playersList.size(); i++) {
System.out.println("Player " + (i + 1) + ", "
+ playersList.get(i).getName() + " Score: " + playersList.get(i).getTotalScore());
playersList.get(i).getFrameScores();
System.out.println("**************");
}
答案 0 :(得分:4)
首先,在列表中的元素上使用一次迭代找到最大分数。然后,使用另一个迭代来寻找哪些玩家拥有最高分并打印出来。
这是上述算法的伪代码:
int maxScore <- Integer.MIN_VALUE
for each player in playerList
if maxScore < player->score then
maxScore <- player->score
end if
end for
//now you have the max score
for each player in playerList
if player-> score == maxScore then
show player info
end if
end for
答案 1 :(得分:0)
试试这个:
double maxScore = playersList.get(0).getTotalScore();
ArrayList<String> maxNames = new ArrayList();
maxNames.add(playersList.get(0).getName());
for (int i = 1; i < playersList.size(); i++) {
if(playersList.get(i).getTotalScore() > maxScore) {
maxScore = playersList.get(i).getTotalScore();
maxNames.clear();
}
if(playersList.get(i).getTotalScore() >= maxScore ) {
maxNames.add(playersList.get(i).getName());
}
}
StringBuilder names = "";
for(int i=0; i<maxNames.size(); i++) {
names.append(maxNames.get(i));
if(i != maxNames.size() - 1) {
names.append(", ");
}
}
System.out.println("The player" + (maxNames.size() > 1 ? "s" : "") + " with the highest score " + (maxNames.size() > 1 ? "are" : "is") + " " + names + ", with a score of " + maxScore + ".");
答案 2 :(得分:-1)
将第一个值指定为max并比较每个值。如果值很大,则将其设置为max并将其与剩余值进行比较。
前者
var max =0;
for(i=o;i<5;i++) {
if(i==0){ var max = a[i]; }
if(max < a[i]) {
max= a[i];
}
}
alert(max);