问题
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?
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();
}
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");
}
}
回答1:
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;
}
}
Output:
--- 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
------------------------------------------------------------------------
来源:https://stackoverflow.com/questions/59292544/sorting-a-text-file-in-javafx