Java – static variable reset on program restart

I have a problem with static counter variables In the super class ("card"), I have a variable to calculate the number of registered cards (this is a ticketing system) It says:

public class Card implements Serializable    {
    private int id;
    public static int nextNr= 000;
    Card next;

    public Card(int t)   {
        id= ++nextNr;
        next= null;
    }
}

This class implements serializable. I use objectstream to write the card to a file

But if I close the program and start it again, it can read and confirm from the file and add the file to my cardregistry again However, the card counter variable in the superclass is reset, and every new card I try to register starts from 001 What on earth did I do wrong? It seems impossible to find any information about this particular problem on the Internet

Solution: I use dataoutputstream to save it on exit and datainputstream to read it on startup I don't know if this is the most effective method, but it works Thank you very much for your comment, it helped me a lot!!!!

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.");
    }
}

Solution

The counter is static Therefore, it is not part of the state of any card instance, and serializing all cards will not save the value of the counter

Save this counter value, reload and explicitly reset it, or get the maximum ID from all deserialized cards at startup and reset the counter to this maximum value

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>