Sorting data from a file into textarea
Hi, i'm coding this simple childrens learning game and to summarise it consists of textfield where user inputs there name and then he/she gets to play this game where at the end you recieve a score. Using read/write methods i made the name and the score to appear on file and then it displays it on textarea. The problem is now i need to sort the scores in the file and display top 10 in the text area. I'm not sure how or where to begin
here is the read/write methods:
Code :
public void writeFile() {
try {
FileWriter write = new FileWriter("text.txt", true);
PrintWriter text = new PrintWriter(write);
text.println( name + " " + score);
text.flush();
write.close();
} catch (IOException ioe)
// writes name from textfield(username) and score from board class
// into text document text.txt
{
ioe.printStackTrace();
}
}
Code :
try {
FileReader fileStream = new FileReader("text.txt");
area.read(fileStream, "text.txt");
fileStream.close();
} catch (FileNotFoundException e)
// gets data from text.txt and reads
// it into textarea called area
{
System.out.println("File not found");
} catch (IOException e)
// this just basic highscores with limited
// capabilities
{
System.out.println("IOException occurred");
}
Re: Sorting data from a file into textarea
I would create an Object that contains one user record- a name and a score. Create a List of these record Objects. Then use a custom Comparator that compares the scores along with the Collections.sort() method to sort the List. Display the first 10 items in the List, and you'll be displaying the top 10 scores (assuming you wrote the Comparator to sort them from high to low).