在JavaFX中对文本文件进行排序 [英] Sorting a Text File in JavaFX

查看:53
本文介绍了在JavaFX中对文本文件进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我可以成功创建一个计分板,然后使用3个变量动态更新此计分板.但是,我现在需要根据得分对记分板进行排序(这里是可变得分),并将前10个得分放在TextArea上.如何使用收藏夹排序"来实现此目的?

So I can successfully create a score board, and then dynamically update this scoreboard with the 3 variables. However, I now need to sort the scoreboard based on the score (so the variable score here) and put the top 10 scores on the TextArea. How do I do this using a Collection Sort?

将3个变量写入文本文件的方法

The method which writes the 3 variables into the Text File

public void newScore() {
    try (BufferedWriter bw = new BufferedWriter(new FileWriter("xxxxx/gameScores.txt", true))) {

        int score = player.getPoints();
        String names = name.getText();
        String levelSelected = choose.getLevel();

        bw.write(names + "          " + score + "          " + levelSelected);
        bw.write("\n");

    } catch (IOException e) {
        e.printStackTrace();
    }

    textArea.clear();
    scoreBoard();
}

我的方法是读取文本文件并动态附加到TextArea(又称计分板)

My method which reads the text file and dynamically appends to the TextArea (AKA, the score board)

public void scoreBoard() {

    File scoreFile = new File("xxxxx/gameScores.txt");

    try (Scanner scoresList = new Scanner(scoreFile)) {
        while (scoresList.hasNext()) {
            textArea.appendText(scoresList.nextLine());
            textArea.appendText("\n");
        }
    } catch (FileNotFoundException ex) {
        System.out.println("ERROR");
    }
} 

推荐答案

我认为您需要创建一个对象来保存代表记分板数据的一个实例的对象.名称:得分:级别.从文件读取数据时,将其作为 ScoreBoardScore List 读取. List< ScoreBoardScore> .对 ScoreBoardScore List 进行排序的一种方法是使用 Collections.sort .下面的示例代码.代码中的注释.

I think you need to create an object to hold what represents one instance of scoreboard data. Name:Score:Level. When you read the data from the file read it an as a List of ScoreBoardScore. List<ScoreBoardScore>. One way to sort the List of ScoreBoardScore is to use Collections.sort. Example code below. Comments in the code.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 *
 * @author Sedrick
 */
public class Main
{
    public static void main(String[] args)
    {
        List<ScoreBoardScore> scoreBoardScores = getScoreFromFile();//get List of ScoreBoardScore from file.
        scoreBoardScores.forEach(System.out::println);//Print scores before sort.

        //sort data
        //This sorts in decending order. To get acending order change if(o1.getScore() < o2.getScore()) to if(o1.getScore() > o2.getScore())
        Collections.sort(scoreBoardScores, Comparator.comparingInt(ScoreBoardScore::getScore).reversed());

        System.out.println("\nAfter Sort:");
        scoreBoardScores.forEach(System.out::println);//Print scores after sort.
    }

    static List<ScoreBoardScore> getScoreFromFile()
    {
        //simulate reading a file and returning a List of Scores
        String fakeFileData = "John Doe     91     8\n"
                            + "jane Doe     100     9\n"
                            + "Kim Johnson     88     7\n"
                            + "Kim Johnson     95     8";

        List<String> lines = new ArrayList(Arrays.asList(fakeFileData.split("\n")));//These simulate the lines of a file.

        List<ScoreBoardScore> scoreBoardScores = new ArrayList();
        for(int i = 0; i < lines.size(); i++)//loop through the lines and split the data based on more than two spaces. I didn't use one space or more because the name has one space.
        {
            String[] splitData = lines.get(i).split("\\s{2,}");//Split on two or more spaces
            scoreBoardScores.add(new ScoreBoardScore(splitData[0], Integer.parseInt(splitData[1]), splitData[2]));//Use the data to create ScoreBoardScores.
        }

        return scoreBoardScores;
    }
}

输出:

--- exec-maven-plugin:1.5.0:exec (default-cli) @ JavaTestingGround ---
ScoreBoardScore{score=91, name=John Doe, level=8}
ScoreBoardScore{score=100, name=jane Doe, level=9}
ScoreBoardScore{score=88, name=Kim Johnson, level=7}
ScoreBoardScore{score=95, name=Kim Johnson, level=8}

After Sort:
ScoreBoardScore{score=100, name=jane Doe, level=9}
ScoreBoardScore{score=95, name=Kim Johnson, level=8}
ScoreBoardScore{score=91, name=John Doe, level=8}
ScoreBoardScore{score=88, name=Kim Johnson, level=7}
------------------------------------------------------------------------
BUILD SUCCESS
------------------------------------------------------------------------
Total time: 1.673 s
Finished at: 2019-12-11T14:25:58-06:00
Final Memory: 12M/40M
------------------------------------------------------------------------

这篇关于在JavaFX中对文本文件进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆