0

I'm designing a banking program, and I have a balance label that shows the balance after each transaction, however, after I close the program it defaults back to it original value

I've tried setting the value of the label to the new desired value, but the program defaults back to the original each time

double newbalance = Double.parseDouble(balance) + Double.parseDouble(deposit);
lbl_ActualBalance.setText(String.valueOf(newbalance));

I expected the value of the label to change indefinitely but it keeps defaulting

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
NoName
  • 1
  • 1
  • If you want to persist the value after the program exits, you need to store it on disk, e.g. in a text file. – hoefling Jul 13 '19 at 10:27
  • how would i go about doing that – NoName Jul 13 '19 at 11:15
  • [How do I save a String to a text file using Java?](https://stackoverflow.com/questions/1053467/how-do-i-save-a-string-to-a-text-file-using-java) – c0der Jul 13 '19 at 14:18

1 Answers1

1

You could also Serialize it. Have the class implement the Serializable interface then when the data is updated just call a save() method:

public void save()
    {   
       FileOutputStream fos = null;
       ObjectOutputStream oos = null;
        try
        {
            fos = new FileOutputStream("saveFile.data");
            oos = new ObjectOutputStream(fos);
            oos.writeObject(this);
        }
        catch(Exception e)
        {
            System.out.println("Error: " + e.getMessage());
        }
        finally
        {
              foo.close();
              oos.close();
        }
    }

then when you load the program up, just call some form of load() method

public void load() {
    ObjectInputStream ois = null;
    FileInputStream fis = null;

    try
    {
        fis = new FileInputStream("saveFile.data");
        ois = new ObjectInputStream(fis);
        lbl_ActualBalance.setText((double)(ois.readObject().lbl_ActualBalance));
    }
    catch(Exception e)
    {
        System.our.ptintln("Error: " + e.getmessage();
    }
    finally
    {
        ois.close();
        fis.close();
    }
}

This way you can easily save/load everything about your system.

johnthomsonn
  • 35
  • 11