我正在尝试按降序输出名称和相应的分数。有一个字符串数组和另一个整数数组,我试图关联两个数组。我使用 Arrays.sort 并尝试获取索引。然后,索引用于将名称排列在与相应分数相似的位置。我有这个代码,但是我得到运行时错误,说很遗憾,你的应用已停止。任何人都可以帮助我做些什么来实现我的目标吗?非常感谢你!
int score[]= new int[4];
score[0]= 10;
score[1]= 50;
score[2]= 20;
score[3]= 60;
String names[] = new String[4];
names[0]= "player1";
names[1]= "player2";
names[2]= "player3";
names[3]= "player4";
Arrays.sort(score);
int index_array[] = new int[4];
int m = 0;
for(m = 0; m <4; m++){
index_array[m]=Arrays.binarySearch(score ,score[m]);
l = index_array[0];
}
for(int i = 0; i<4; i++){
if(l == score[i]){
j = i;
}
}
String name = names[m];
show.setText(name + " " + Integer.toString(l));
答案 0 :(得分:2)
您需要关联分数和用户名。目前,您通过数组索引关联它们。当您对分数进行排序时,分数的指数会发生变化。
尝试这样的事情:
class Score implements Comparable<Score>
{
int score;
String player;
public Score(int theScore, String thePlayer)
{
score = theScore;
player = thePlayer;
}
public int compareTo(Score)
{
... compare based on the int score value ...
}
... getters. setters optional ...
}
List<Score> scoreList = new ArrayList<Score>();
... fill scoreList with Score objects. ...
Collections.sort(scoreList);
答案 1 :(得分:1)
创建保持玩家姓名和分数的玩家模型,然后使用比较器按分数对玩家进行排序。
玩家模型:
class Player {
private String name;
private int score;
public Player(String name, int score) {
this.name = name;
this.score = score;
}
public String getName() {
return name;
}
public int getScore() {
return score;
}
public String toString() {
return "name=" + name + "; score=" + score;
}
}
比较
class PlayerComparator implements Comparator<Player> {
public int compare(Player p1, Player p2) {
return p1.getScore() < p2.getScore() ? -1
: p1.getScore() > p2.getScore() ? 1 : 0;
}
}
使用示例:
public class PlayerTest {
public static void main(String[] args) {
int score[]= new int[4];
score[0]= 10;
score[1]= 50;
score[2]= 20;
score[3]= 60;
String names[] = new String[4];
names[0]= "player1";
names[1]= "player2";
names[2]= "player3";
names[3]= "player4";
Player[] players = new Player[names.length];
for(int i = 0; i < names.length; i++) {
players[i] = new Player(names[i], score[i]);
}
Arrays.sort(players, new PlayerComparator());
}
}
答案 2 :(得分:0)
这是一种设计气味。你不应该有两个并行数组。相反,你应该有一个Player对象数组,每个Player都有一个名字和一个分数。
按名称或分数存储球员的数量将非常简单。
Java是一种OO语言。使用对象。
public class Player
private final String name;
private int score;
public Player(String name, int score) {
this.name = name;
this.score = score;
}
public String getName() {
return name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
}
...
Player[] players = new Player[4];
players[0] = new Player("player1", 10);
...