I have a problem with a static counter variable. In a super class ("Card") I have a variable that counts the amount of cards that gets registered (It's a ticket system). It is written like this:
public class Card implements Serializable {
private int id;
public static int nextNr= 000;
Card next;
public Card(int t) {
id= ++nextNr;
next= null;
}
}
The class implements Serializable and I use ObjectStream to write out the cards to a file.
But if I close the program and start it up again, it can read from the file and confirms and add the files to my cardregistry again. BUT, the card counter variable in the super class is reseted, and every new card I try to register starts from 001 again. What am I doing wrong? Cant seem to find anything about this particular problem on the net.
Solution: I used a DataOutputStream to save it on exit, and DataInputStream to read it on startup. I don't know if this is the most efficient way to do this, but it worked. Thanks alot for you comments, it helped me out alot!!!!
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.");
}
}