gpt4 book ai didi

java - 加载游戏分数

转载 作者:行者123 更新时间:2023-12-01 14:37:49 24 4
gpt4 key购买 nike

在我目前正在开发的游戏中,我希望当你开始游戏时,你可以获得退出前的分数。我已经使用此代码为乐谱创建了一个保存文件。

                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"

最佳答案

如果您执行 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);

关于java - 加载游戏分数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16317806/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com