【问题标题】:Loading score for a game加载游戏得分
【发布时间】:2013-05-01 12:06:39
【问题描述】:

在我目前正在开发的游戏中,我希望在开始游戏时获得退出前的分数。我已经用这段代码为乐谱制作了一个保存文件。

                try{
                    File getScore = new File("Score.dat");
                    FileOutputStream scoreFile = new FileOutputStream(getScore);
                    byte[] saveScore = score.getBytes();
                    scoreFile.write(saveScore);
                }catch(FileNotFoundException ex){

                }catch(IOException ex){

                }

分数显示为字符串,因此在开始游戏时必须将 .dat 文件中的分数作为字符串获取,以便我可以将分数字符串与开始时生成的字符串相等。我已经尝试使用下面显示的代码。

        try{
            BufferedReader br = new BufferedReader(new FileReader("Score.dat"));
            score = br.toString();
        }catch (FileNotFoundException ex){

        }

但是当我使用该代码时,我会收到此错误消息。

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "java.io.BufferedReader@313159f1"

【问题讨论】:

  • scores 是什么类型?
  • @TheMerovingian 这是一个String,但每次我更新它时,我都会将其更改为int,在int 上加10,然后将其转回String
  • 1.您应该通过调用scoreFile.close() 关闭FileOutputStream; 2.你应该使用br.readLine()而不是br.toString()

标签: java file save bufferedreader filereader


【解决方案1】:

如果您执行br.toString(),它会从您的 BufferedReader 对象上的类对象调用toString() 方法。所以它会打印缓冲对象的内存地址:

public String toString() {
           return getClass().getName() + "@" + Integer.toHexString(hashCode());
 } 

这就是你得到NumberFormatException 的原因,因为你不能将String 分配给score(我想这是一个int 变量)。

此外,您绝对不会寻找它,因为您希望将文本存储在文件中。如果你想从缓冲区中读取一行,你只需要这样做:

 String line = br.readLine();
    int value = Integer.parseInt(line);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-11
    • 2018-06-04
    • 1970-01-01
    相关资源
    最近更新 更多