You need to enable JavaScript to run this app. Java贪吃蛇游戏用txt存储最高分无法读取始终显示0报错问题
优惠活动
大模型
产品
解决方案
定价
更多

Java贪吃蛇游戏用txt存储最高分无法读取始终显示0报错问题

Java贪吃蛇最高分读写问题修复方案

问题根因

  • 读写路径不一致:写入分数时使用绝对路径C:\\Users\\wolf\\OneDrive\\Desktop\\Snake Game\\build\\classes\\scoredata.txt,读取时使用相对路径scoredata.txt,程序运行时的工作目录通常不是上述classes目录,导致读取时找不到文件,抛出IO异常,触发"ERROR reading scores"报错。
  • 最高分比较逻辑倒置:现有判断条件为if (score2 <= highScore)才更新最高分,而highScore初始值为0,仅当读取到的分数小于等于0时才会触发更新,因此最高分始终显示为0。
  • 异常处理不完善:NumberFormatException的捕获块为空,若文件中存在非数字内容,会导致分数读取异常但无法定位问题。
  • 逻辑顺序不合理:现有代码先写入本次分数再读取历史最高分,本次游戏的分数不会被计入本次展示的最高分统计。

修复后代码

// 统一分数文件路径为常量,避免读写路径不一致
private static final String SCORE_FILE_PATH = "C:\\Users\\wolf\\OneDrive\\Desktop\\Snake Game\\build\\classes\\scoredata.txt";
private int score = 0;
private int highScore = 0; 
public void gameOver(Graphics g){
        // 先读取历史最高分
        File file = new File(SCORE_FILE_PATH);
        try  {
            BufferedReader reader = new BufferedReader(new FileReader(file));
            String line = reader.readLine();
            while (line != null)          
            { 
                try {
                    int score2 = Integer.parseInt(line.trim());   
                    // 修正比较逻辑:分数大于当前最高分时才更新
                    if (score2 > highScore)                     
                    {  
                        highScore = score2; 
                    }
                    line = reader.readLine();
                } catch (NumberFormatException e1) {
                    // 增加异常日志,方便定位无效分数行
                    System.err.println("忽略无效分数记录:" + line);
                }
            }
            reader.close();
        } catch (IOException ex) {
            System.err.println("读取分数文件失败:" + ex.getMessage());
        }

        // 写入本次游戏分数
        try {
            PrintWriter writer = new PrintWriter(new FileWriter(SCORE_FILE_PATH, true));
            writer.println(score);     
            writer.close();
            // 将本次分数和历史最高分对比,更新展示值
            if(score > highScore){
                highScore = score;
            }
        } catch(Exception ex){
            System.err.println("写入分数文件失败:" + ex.getMessage());
        }

        // 原有UI展示逻辑不变
        String msg1 = "Game Over ";
        String msg2 = "SCORE IS " +score ;
        String msg4 = "HIGHSCORE  " +highScore ;  
        Font font = new Font("SAN_SERIF", Font.BOLD, 14);
        FontMetrics metrices = getFontMetrics(font);
        
        g.setColor(Color.WHITE);
        g.setFont(font);
        g.drawString(msg1, (300 - metrices.stringWidth(msg1)) / 2 , 300/2);
        g.setColor(Color.RED);
        g.drawString(msg2, (300 - metrices.stringWidth(msg2)) / 2 , 250/2);
        g.setColor(Color.RED);
        g.drawString(msg4, (300 - metrices.stringWidth(msg4)) / 2 , 200/2);
}

内容的提问来源于stack exchange,提问作者rage_wolf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.10 12:18:03