2013-06-07 3 views
-2

현재 저는 작은 문제가 있습니다. 저는 Java로 게임을 만들고 있는데, 최고 점수를 얻고 있습니다. 나는 플레이어의 이름과 점수를 텍스트 파일에 저장했다. 인쇄를 시도 할 때 텍스트 파일의 순서대로 보여 주므로 어떻게 정렬하여 가장 높은 점수를 먼저 사용했는지 보여줍니다. 텍스트 파일에서Java를 사용하여 가장 높은 숫자로 텍스트 파일을 정렬하는 방법

예 :

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

내가 원하는 방법은 :

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

[Array # sort()] (http://docs.oracle.com/javase/7//docs/api/java/util/Arrays.html#sort (int [])) – Smit

+0

코드 란 무엇입니까? 파일에 인쇄 하시겠습니까? 인쇄 및 순서 재 지정 대신에 순서대로 인쇄하는 것이 좋습니다. (인쇄 코드를 변경할 수없는 한 ...) – acdcjunior

+1

우리가 당신을 도와 줄 수 있도록 코드를 보여주십시오. –

답변

1

종류의 Collections.sort(list);

0

이를 구현할 수있는 여러 가지 방법이 있습니다 사용해보십시오. Java에서 여러 항목을 정렬하는 방법에 대한 도움말은 this link을 확인하십시오.

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 
관련 문제