I made a high score feature for my game. It works fine but every time I close the program and run it back the high score reset to 0. Please help me to fix this. For example:
1st time: My high score is 50 and it saves my score to file
2nd time: I close the game and run it back my score is 30. It still saves it to high score file
This is because the high score every time it runs is 0.
Here is my code to check high score. Basically, it will compare scores and high scores and then store in the file.
private String highScore = "Nobody:0"; //I think this is the problem because highscore =0 at start
public void CheckHighScore() {
if (score > Integer.parseInt((highScore.split(":")[1]))) {
String name = JOptionPane.showInputDialog("You set a new highScore. What 's your name?");
highScore = name ":" score;
File scoreFile = new File("highscore.dat");
if (!scoreFile.exists()) {
try {
scoreFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
FileWriter writeFile = null;
BufferedWriter writer = null;
try {
writeFile = new FileWriter(scoreFile,true);
writer = new BufferedWriter(writeFile);
writer.write(this.highScore);
writer.newLine();
}
catch (Exception e) {
}
finally {
try {
if (writer != null)
writer.close();
}
catch (Exception e) {}
}
}
}
CodePudding user response:
can you please answer one question?
i.) Do you want you last list of highscores to be available when the game loads? if yes then your not reading anything from the file but simply writing to it. You can simply fetch the highest from the list.
-> if the first part is true the yes, String highScore = "Nobody:0"
is wrong since your initializing the value to zero every time, instead it should be read from the file where the data has been stored.
You can try this to read specific lines:
try (Stream<String> all_lines = Files.lines(Paths.get("myfile.txt"))) { specific_line_n = all_lines.skip(n-1).findFirst().get(); }