【发布时间】:2020-02-01 00:49:15
【问题描述】:
我有一个包含测验和活动的应用程序,我希望在其中获得前 5 名得分的玩家。 我有 2 个 ArrayList,其中一个存储分数,另一个存储玩家的姓名。 我设法用分数列出了列表,但我不知道如何在同行分数旁边加上正确的名字。
我所拥有的图片:https://i.imgur.com/MX9qUP2.png
还有一张我正在寻找的图片:https://i.imgur.com/6PHHsIt.png
我尝试过使用 Map,但我不知道不能存储 2 个相同的键,所以这是不可能的,但可能有一种方法可以让某种带有索引的数组列表,但可以有 2 个不同的信息,我不知道。
我的 2 个数组列表:
public static ArrayList<Integer> scoresList = new ArrayList<>();
public static ArrayList<String> namesList = new ArrayList<>();
我获得 5 个最好成绩的方法:
public class HistoryActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_history);
TextView first = (TextView) findViewById(R.id.history_activity_first);
TextView second = (TextView) findViewById(R.id.history_activity_second);
TextView third = (TextView) findViewById(R.id.history_activity_third);
TextView fourth = (TextView) findViewById(R.id.history_activity_fourth);
TextView fifth = (TextView) findViewById(R.id.history_activity_fifth);
Collections.sort(scoresList, Collections.reverseOrder());
first.setText("Best score is : " + scoresList.get(0));
if (scoresList.size() >= 2) {
second.setText("2nd best score is : " + scoresList.get(1));
}
if (scoresList.size() >= 3) {
third.setText("3rd best score is : " + scoresList.get(2));
}
if (scoresList.size() >= 4) {
fourth.setText("4th best score is : " + scoresList.get(3));
}
if (scoresList.size() >= 5) {
fifth.setText("5th best score is : " + scoresList.get(4));
}
}
}
谢谢
【问题讨论】:
-
写这样的东西不是那么简单:
first.setText("Best score is : " + scoresList.get(0) + "-" + namesList .get(0));吗?您也可以使用 ListView(或 RecyclerView)和适配器来完成这项工作 -
但是 nameList.get(0) 与 scoreList.get(0) 不匹配,因为有一种排序允许我访问 scoreList @Shermano 的最大值
-
为什么你有一个
nameList和一个scoreList,而你可以有一个playerList和一个class Player { private String name; private long score; },然后创建一个Comparator<Player>来按分值对它们进行排序?跨度>
标签: java android android-studio arraylist collections