我有一个JFrame和一个获取图表的JPanel。该图表有10个垂直位置显示玩家(另外1个用于菜单),3个水平位置显示"#"、"姓名"、"分数"。在每个回合,玩家输入自己的名字,而他的分数被保存。我想把他/她的名字印在他/她每轮的分数上。所以如果进行6场比赛,就会有6个名字和他们的分数。所有的分数必须从高到低排序
使用的变量有:
private int score;
private String[] playerscore = {"#","Name", "Score"};
private String[][] singleplay = {{"#","Name","Score"},{"1","----------","--"},{"2","----------","--"},{"3","----------","--"},{"4","----------","--"},{"5","----------","--"},{"6","----------","--"},{"7","----------","--"},{"8","----------","--"},{"9","----------","--"},{"10","----------","--"}};
我认为必须有两个数组的名称和字符串,这将被用来获得所有的数据从"单人游戏"和组织。我使用:
int [] ascore = {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1};
String [] aname = {"","","","","","","","","",""};
我需要帮助使表组织,同时也增加了"图表已满"的条件。例如:"如果得分低于10号球员的得分,什么都不做。我有一个想法,x位置的内容应该保存在分数和名字中。我尝试保存内容,以便以后进行组织:
ascore [0] = Integer.parseInt(singleplay[1][2]);
aname [0] = singleplay[1][1];
在组织'ascore'和' name'之后,我将使用:
打印它singleplay[x][2] = Integer.toString(ascore[y]);
singleplay[x][1] = aname [y];
谢谢你的帮助
每个记录都有名称和分数。您可以创建类Record:
class Record {
private String name;
private int score;
public Record(String name, int score){
this.name = name;
this.score = score;
}
public String getName(){
return name;
}
public int getScore(){
return score;
}
}
然后你可以将这些记录保存在一个列表中,例如ArrayList:
ArrayList<Record> records = new ArrayList<Record>();
records.add(new Record("Joe", 5));
records.add(new Record("Kathy", 7));
那么你可以对这个列表进行排序
Collections.sort(records, new GameRecordsComparator());
where GameRecordComparator is:
class GameRecordComparator implements Comparable<Record> {
@Override
public int compare(Record r1, Record r2) {
return r1.getScore() - r2.getScore();
}
}
您希望最多有10条记录,因此在插入之前您可以检查列表大小
if (records.size()<10){
records.add(...); // add your newly created record
} else if (records.get(9).getScore()<score) {
// elements in a list are 0-based, 9 means 10th element
// score is a score of a new element, which user wants to enter
records.remove(9);
records.add(...); // add your newly created record
Collections.sort(records, new GameRecordsComparator());
}