I'm trying to create a highscore method for one of my programs but it is not working as I want it to. The problem im having is how to tell the program from which line in a txt file (Highscore file) it is supposed to write to.
I have done as follows:
I created a method that finds the number of lines in a file
public static int countline (String filnamn)throws IOException {
BufferedReader inström1 = new BufferedReader
(new FileReader(filnamn));
int lines = 0;
while(inström1.readLine() != null) {
++lines;
}
inström1.close();
return lines;
}
Then i tried, using a for loop, to print a score to a text file everytime the program hits an empty space in the txt file:
PrintWriter utström1 = new PrintWriter
(new BufferedWriter
(new FileWriter("Highscores")));
for(int i = 0; i < countline("Highscores")+1; i++) {
if(inström1.readLine() == null) {
utström1.println(namn + ", " + (double)100*rätt/(rätt+fel) + "% rätt" + "\n");
}
}
utström1.close();
When I run the program it only writes over the last highscore in the file. How could I fix this?