试图在处理游戏中打印高分并将其保存到外部文件中以供再次读取

问题描述 投票:1回答:1

我现在正在用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;
}
java
1个回答
-1
投票

下午好,很难帮助解决您的代码片段中缺少的很多内容,但是您可以尝试执行以下操作:

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();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.