我最近制作了一款Snake游戏,其功能可以存储并找到他的最佳成绩。但不幸的是,每次将分数保存到文件中时,它都会删除以前的文件内容。有什么办法可以避免吗?正如在下面的代码中可见,我已经制作了3种方法。第一个是将分数保存到文件中。最后一个是找到最好的分数。
package matajus.snake;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class Score {
private File file;
public static int score;
private static final String fileName = "BestScores.txt";
public Score() {
file = new File(fileName);
if(!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void saveToFile() throws FileNotFoundException {
PrintWriter print = new PrintWriter(fileName);
print.println(score);
print.close();
}
public int findBestScore() {
List<Integer> lines = new ArrayList<Integer>();
Scanner input;
int bestScore = 0;
try {
input = new Scanner(file);
if(linesNumber() > 0) {
for(int i = 0; i < linesNumber(); i++) {
String readLine = input.nextLine();
int line = Integer.parseInt(readLine);
lines.add(line);
}
bestScore = Collections.max(lines);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return bestScore;
}
private int linesNumber() throws FileNotFoundException {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line;
int lines = 0;
try {
while((line = reader.readLine()) != null) {
lines++;
}
} catch (Exception e) {
e.printStackTrace();
}
return lines;
}
}
答案 0 :(得分:0)