ここでJavaを勉強する男。学校で課題があり、簡単な GUI を使って小さなスター ウォーズ ゲームを作成しました。SaveToFile()
メソッドとReadFromFile()
メソッドで、メソッドが例外をスローします。これで問題ありません。すべてが機能します。
しかし、割り当てには、「一部のメソッドは例外をスローする可能性があります。これらは合理的に処理する必要があります。」これが何を意味するのか分かりません。コードの重複を回避しようとすることと関係があるようです。ヒントはありますか?再利用できるエラーのメソッドを作成することですか?
これが私のコードです:
private void readFromFile()
{
try{
gui.makeInVisible();
FileInputStream fis = new FileInputStream("Savegame.obj");
ObjectInputStream ois = new ObjectInputStream(fis);
Battleground battleground = (Battleground) ois.readObject();
GUI gui = new GUI(battleground);
BattleController bc = new BattleController(gui, battleground);
ois.close();
}
catch (IOException e) {
gui.updateActionField("Something went wrong... Did you delete the file Savegame.obj while playing?");
e.printStackTrace();
}
catch (ClassNotFoundException f) {
System.out.println("Woops. This game looks broken! Did you delete the whole battleground class?");
}
}
private void saveToFile() { try{ // Serialize data object to a file ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("Savegame.obj")); out.writeObject(battleground);
Serialize data object to a byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream() ;
out = new ObjectOutputStream(bos) ;
out.close();
// Get the bytes of the serialized object
byte[] buf = bos.toByteArray();
} catch (IOException e) {
gui.updateActionField("Something went wrong with saving the file. And we really don´t know what I am afraid!");
}
}
ありがとう。