-2

我目前有一个小问题,我正在用 Java 制作一个游戏,并且我正在为它制作一个高分。我让它将播放器的名称和分数保存到一个文本文件中。当我尝试将其打印出来时,它显然按文本文件的顺序显示,我将如何对其进行排序,以便它首先使用最高分。

文本文件中的示例:

John: 12
Bert: 16
Oscar: 18
Eric: 25
Carl: 9

我想要它:

Eric: 25
Oscar: 18
Bert: 16
John: 12
Carl: 9
4

2 回答 2

1

使用一个有序的集合,就像TreeMap它保持其条目(键值映射)在其键的自然顺序中一样。因为,您想对高分进行排序,将您的分数作为键,将玩家姓名作为它们的值。

// instantiate your sorted collection
Map<Integer, String> highestScores = new TreeMap<Integer, String>();

// setup a file reader
BufferedReader reader = new BufferedReader(
                        new FileReader(new File("/path/to/file")));

String line = null;
while ((line = reader.readLine()) != null) { // read your file line by line
    String[] playerScores = line.split(": ");
    // populate your collection with score-player mappings
    highestScores.put(Integer.valueOf(playerScores[1]), playerScores[0]);
}

// iterate in descending order
for (Integer score : highestScores.descendingKeySet()) {
    System.out.println(highestScores.get(score) + ": " + score);
}

输出

Eric: 25
Oscar: 18
Bert: 16
John: 12
Carl: 9

编辑:
很有可能两个或更多的玩家可以有相同的高分。因此,排序后的集合必须稍微复杂一些,但如果您已经理解了上面的集合,那么理解这个集合就不会遇到麻烦。

与其将分数映射到一个玩家,我们现在必须将它映射到一个List玩家(具有相同的高分):

// {key - value} = {high score - {list, of, players}}
TreeMap<Integer, List<String>> highestScores =
                               new TreeMap<Integer, List<String>>();

BufferedReader reader = new BufferedReader(
                        new FileReader(new File("/path/to/file")));

String line = null;
while ((line = reader.readLine()) != null) {
    String[] playerScores = line.split(": ");
    Integer score = Integer.valueOf(playerScores[1]);
    List<String> playerList = null;

    // check if a player with this score already exists
    if ((playerList = highestScores.get(score)) == null) { // if NOT,
        playerList = new ArrayList<String>(1); // CREATE a new list
        playerList.add(playerScores[0]);
        highestScores.put(Integer.valueOf(playerScores[1]), playerList);
    } else { // if YES, ADD to the existing list
        playerList.add(playerScores[0]);
    }
}

// iterate in descending order
for (Integer score : highestScores.descendingKeySet()) {
    for (String player : highestScores.get(score)) { // iterate over player list
        System.out.println(player + ": " + score);
    }
}

输出

Eric: 25
Oscar: 18
Bert: 16
John: 12 *
Jane: 12 *
Carl: 9
于 2013-06-07T17:22:47.223 回答
1

尝试使用排序 Collections.sort(list);

于 2013-06-07T16:55:49.913 回答