我现在正在用Java开发一个项目,基本上就是游戏蛇。我通过将高分打印到外部txt文件上来完成它,以便在高分被破坏时可以读写它们。似乎不希望我解析从文件读取的行。我需要成为一个整数,以便可以将其与最新分数进行比较。
BufferedReader reader;
PrintWriter output;
String line = "1";
reader = createReader("SnakeFile.txt");
output = createWriter("SnakeFile.txt");
try {
line = reader.readLine();
boolean t = true;
while (t) {
String score = line;
int x = Integer.parseInt(score);
if (x < snake.bodyLength) {
System.out.println("New High Score" + snake.bodyLength);
output.println(snake.bodyLength);
}
// line = reader.readLine();
t = false;
}
// highScore = reader.readLine();
// highScore ="5";
// output.flush(); // Writes the remaining data to the file
output.close(); // Finishes the file
} catch (IOException e) {
e.printStackTrace();
line = null;
}
下午好,很难帮助解决您的代码片段中缺少的很多内容,但是您可以尝试执行以下操作:
private static String FILENAME = "SnakeFile.txt";
public static void main(String[] args) {
File file = new File(FILENAME);
try {
file.createNewFile();
List<String> fileContents = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8);
int score = 1;
if (fileContents != null) {
score = Integer.parseInt(fileContents.get(0));
while (true) {
if (score < snake.bodyLendth) {
System.out.println("New High Score" + snake.bodyLength);
output.println(snake.bodyLength);
}
break;
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}