Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save object variables after closing my program?

I'm trying to learn Java and OOP by creating a monopoly banker program. However, I would like some object variables to be saved after I exit the program, so that after playing half of a monopoly game I can exit my program and then restart it with all the player balances saved.

I'm guessing this requires some sort of database?

Here is a section of my code; I am trying to save the "balance" variable for all of my objects (players) after I exit my program.

   public class Monopoly {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    // TODO code application logic here
    //creates the users (name classes)
players player1 = new players();
players player2 = new players();
players player3 = new players();
players player4 = new players();



while (true)  {

player1.balance=player1.finalbalance;
player2.balance=player2.finalbalance;
player3.balance=player3.finalbalance;
player4.balance=player4.finalbalance;
like image 361
user3133300 Avatar asked Jan 04 '14 18:01

user3133300


People also ask

How do you save variables in Java?

In a debugger breakpoint stack frame, right click on a variable, you will see "Save Value" and "Load Value..." on the menu. "Save Value" will directly save the selected value.

Where are object variables stored?

Object storage takes each piece of data and designates it as an object. Data is kept in separate storehouses versus files in folders and is bundled with associated metadata and a unique identifier to form a storage pool.


2 Answers

I would just serialize this object and deserialize it after you resume your game. I think it is the best way. Here you can find the way how to do that. http://www.tutorialspoint.com/java/java_serialization.htm

like image 136
Evan Sharry Avatar answered Oct 28 '22 17:10

Evan Sharry


Maybe I didn't really understant your question but if you need a method to catch the exit before the program exit (CTRL-C for instance) you van use an "exit hook", usefull also to free connection

see

Useful example of a shutdown hook in Java?

like image 27
venergiac Avatar answered Oct 28 '22 17:10

venergiac