简体   繁体   中英

Sorting a 2D string array in Java in descending order and writing it to a file

So I have to read out a string from a file in Java. It's for a highscore system. Each line of the file contains something similiar like this: "24/Kilian". The number in front of the / is the score and the text after the / is the name.

Now, my problem is that I have to sort the scores descending and write them back into the file. The new scores should overwrite the old ones.

I tried it but I can't get it working properly. I already wrote some code which reads the score + name line by line out of the file.

public static void sortScores() {
        String [][]scores = null;
        int i = 1;
        try (BufferedReader br = new BufferedReader(new FileReader("score.txt"))) {
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
                scores[i][0] = line.substring(0, line.indexOf("/"));
                scores[i][1] = line.substring(line.indexOf("/"), line.length());
                i++;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

So, this code basically writes the score and the name in a 2D array like this:

score[0][0] = "24";
score[0][1] = "Kilian";

score[1][0] = "33";
score[1][1] = "Name";

score[2][0] = "45";
score[2][1] = "AnotherName";

I hope someone can help me with my problem.

Use Arrays.sort(arr, comparator) with a custom comparator:

Arrays.sort(theArray, new Comparator<String[]>(){

    @Override
    public int compare(final String[] first, final String[] second){
        // here you should usually check that first and second
        // a) are not null and b) have at least two items
        // updated after comments: comparing Double, not Strings
        // makes more sense, thanks Bart Kiers
        return Double.valueOf(second[1]).compareTo(
            Double.valueOf(first[1])
        );
    }
});
System.out.println(Arrays.deepToString(theArray));

I'd recomend you to make a new class Score which holds your data (score + name) and add a new instance of Score into a ArrayList for each row you read from the file. After that you can implement a Comparator and sort your ArrayList . It's much easier because you don't know how big your string array will get and you need to know that when you're working with arrays.

public class Score {
    public Score(int score, String name) {
        this.score = score;
        this.name = name;
    }

    int score;
    String name;

    // getter
}


List<Score> scoreList = new ArrayList<>();
String line;
while ((line = br.readLine()) != null) {
    scoreList.add(new Score(Integer.parseInt(line.substring(0, line.indexOf("/"))), line.substring(line.indexOf("/"), line.length())));
}

Collections.sort(scoreList, new Comparator<Score>() {
    public int compare(Score s1, Score s2) {
        return s1.getScore() - s2.getScore();
    }
}

// write to file

You can use java.util.Arrays 's sort -Method:

Arrays.sort(scores, (a, b) -> -a[0].compareTo(b[0]));

But this lead to the case that "3" will be above "23". So probably you should create new class which holds the value and use an ArrayList

You can try it:

 HashMap<Integer, String > map = new HashMap<>();

    try (BufferedReader br = new BufferedReader(new FileReader("score.txt"))) {
        String line;
        while ((line = br.readLine()) != null) {
            System.out.println(line);
            String[] lines = line.split("/");
            map.put(Integer.valueOf(lines[0]),lines[1]);
        }
        SortedSet<Integer> keys = new TreeSet<Integer>(map.keySet());
        keys.forEach(k -> System.out.println(map.get(k).toString() + " value " + k ));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM