所以,我们有个任务要做一个猜谜游戏。程序必须生成一个数字,用户必须猜测。在用户猜对了之后,程序会显示“高分”(用户在猜对了之前要猜多少次)。
然后,我们应该将此高分保存在文本文件中,以便将其保存在计算机上,如果您重新启动计算机,它将不会丢失。我正在纠结的是程序应该如何读取我保存的文件。
这是我的“写代码”:
try {
FileOutputStream write = new FileOutputStream
DataOutputStream out = new DataOutputStream(write);
out.writeBytes(""+highscore);
write.close();}
catch(IOException ioException ){
System.err.println( "Could not write file" );
return;}很好,但我不知道怎么再读一遍。我的“阅读代码”:(我猜到了,我不知道这是否可行)
try{
FileInputStream read = new FileInputStream
DataInputStream in = new DataInputStream(read);
in.readBytes(""+highscore);
JOptionPane.showMessageDialog(null, "Your highscore is" + highscore);
catch(IOException ioException ){
System.err.println( "Could not read file" );
return;}现在,我不知道in.readBytes(""+highscore);命令是否正确。我只是猜到了(我认为如果out.writeBytes(""+highscore);成功了,那么read也一定要工作)
如果readBytes是正确的命令,那么我将得到以下错误:
The method readBytes(String) is undefined for the type DataInputStream
我该怎么做?
一些信息:高分是和int。
发布于 2013-09-04 15:22:42
例如,如果highscore是int,则需要将int写入文件。你可以用
DataOutputStream out = new DataOutputStream(write);
out.writeInt(highscore);然后用
DataInputStream in = new DataInputStream(read);
int highscore = in.readInt();类DataInputStream没有readBytes()。这就是为什么您的程序不编译。
DataIOStream类的全部目的是读写
底层的原始Java数据类型。以一种独立于机器的方式流动。
因此,使用与highscore的数据类型相对应的方法。
https://stackoverflow.com/questions/18617657
复制相似问题