My assignment is to recreate a game. One of the requirements is to have a txt. file that saves the top 10 scores in the game and updates them as the user continues to play. The file should also be accessible to the user to view.
So far, I've been able to create the file and add the score to it but I've tried over and over to add new scores without erasing the old ones, I've tried new FileWriter("file", true)
and other methods that were suggested on-line but none of them work.
I can't see how I can sort the data and replace the scores as higher scores come in if I can't even keep more than one score on the txt. file. Please let me know an easy way to do this, I'm extremely new to programming.
public static void scores() {
PrintWriter output = null;
try {
output = new PrintWriter(new FileWriter("/Users/name/Desktop/javaoutput.txt"));
} catch (IOException e) {
e.printStackTrace();
}
output.println(counter);
output.close();
}
It makes sense to me logically to create an array, something is still wrong though. Any idea how I should fix it from here?
UPDATED CODE:
public static void scores() {
int temp;
int line;
PrintWriter output = null;
try {
output = new PrintWriter(new FileWriter("/Users/name/Desktop/javaoutput.txt"));
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedReader input = null;
try {
input = new BufferedReader(new FileReader("/Users/name/Desktop/javaoutput.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
line = (Integer.parseInt(input.readLine()));
} catch (IOException e) {
e.printStackTrace();
}
for (int i = 0; i < 10; i++) {
try {
topscores[i] = (Integer.parseInt(input.readLine()));
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
topscores[10] = counter;
for (int i = 0; i < 11 - 1; i++) {
for (int j = 0; j < 11 - 1 - i; j++) {
if (topscores[j] > topscores[j + 1]) {
temp = topscores[j];
topscores[j] = topscores[j + 1];
topscores[j + 1] = temp;
}
}
}
for (int i = 0; i < 10; i++) {
output.println(topscores[i]);
}
output.close();
for (int i = 0; i < 10; i++) {
topscoress.setText(" " + topscores[i]);
}
}
}