0

So, we got an assignment to make a guessing game. The program has to generate a number and the user has to guess. After the users guesses right, the program shows the "Highscore" (how many times the user had to guess before he got it right).

Then we should save this highscore in a text-file, so that it is saved on the computer, and if you restart the computer it will not be lost. What I am struggeling with is how the program is supposed to read the file I saved.

This is my "write-code":

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;}

Which works fine, but I don't know how to read it again. My "read-code": (I just guessed, I don't know if this would work)

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;}

Now, I dont know if the in.readBytes(""+highscore); command is correct. I just guessed (I thought if out.writeBytes(""+highscore); worked then surely read has to work too)

If readBytes is the correct command then I get this error :

The method readBytes(String) is undefined for the type DataInputStream

What am I supposed to do?

Some information: The highscore is and int.

4

1 に答える 1

1

たとえば、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

于 2013-09-04T15:22:42.220 に答える