每次通过后订购/组织最高到最低的字符串[] []

时间:2014-05-16 23:04:07

标签: java arrays swing multidimensional-array organization

我有一个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和aname中。我试图通过以下方式保存内容以便进行组织:

ascore [0] = Integer.parseInt(singleplay[1][2]);
aname [0] = singleplay[1][1];

在组织'ascore'和'aname'之后,我将使用以下方式打印它:

singleplay[x][2] = Integer.toString(ascore[y]);
singleplay[x][1] = aname [y];

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

每条记录都有一个名称和分数。您可以创建类记录:

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());

GameRecordComparator是:

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());
}