静的カウンター変数に問題があります。スーパークラス(「カード」)には、登録されるカードの量をカウントする変数があります(チケットシステムです)。次のように書かれています。
public class Card implements Serializable {
private int id;
public static int nextNr= 000;
Card next;
public Card(int t) {
id= ++nextNr;
next= null;
}
}
このクラスは Serializable を実装し、ObjectStream を使用してカードをファイルに書き出します。
しかし、プログラムを閉じて再度起動すると、ファイルから読み取って確認し、ファイルをカードレジストリに再度追加できます。しかし、スーパークラスのカードカウンター変数はリセットされ、登録しようとするすべての新しいカードは再び001から始まります。私は何を間違っていますか?ネット上でこの特定の問題について何も見つけられないようです。
解決策: DataOutputStream を使用して終了時に保存し、DataInputStream を使用して起動時に読み取りました。これがこれを行う最も効率的な方法かどうかはわかりませんが、うまくいきました。コメントありがとうございます、とても助かりました!!!!
abstract public class Card implements Serializable {
private int type;
private int cardNr;
private static int nextNr = readCardNr();
Card next; //COllections or not.. hmmmm
public Card(int t) {
cardNr= ++nextNr;
next= null;
type = t;
writeCardNr();
}
public int getType(){
return type;
}
public void setCardNr(int i) {
cardNr= i;
}
public int getCardNr() {
return cardNr;
}
public static int readCardNr() {
try(DataInputStream inn= new DataInputStream(new FileInputStream("KortNummer"))) {
nextNr= inn.readInt();
inn.close();
return nextNr;
}
catch(FileNotFoundException fnfe) {
skrivMld("Fant ingen tidligere registrerte kort. Starter nytt kortregister.");
nextNr= 000;
return nextNr;
}
catch(EOFException eofe) {
System.out.println("End of file");
}
catch(IOException ioe) {
skrivMld("Feilmelding: IO Exception");
}
return nextNr;
}
public void writeCardNr() {
try(DataOutputStream ut= new DataOutputStream(new FileOutputStream("KortNummer"))){
ut.writeInt(cardNr);
}
catch(IOException ioe) {
skrivMld("Problem med skriving til fil.");
}
}