0

Hi I am very new to Java and I'm not even sure If I am asking a valid question. But I will try to describe my it as best as I can.

I am trying to save my data permanently but it keep restarting whenever I re-run the program or when I delete stuff in my main method. For example, consider the following code:

public class Player {
    private int wins;

    public Player {
        wins = 0; 
    }

    public getWins() {
        return wins;
    }

    public addWins() {
        this.win++;
    }
}

public class Game {
    public static void main(String[] args) {
        Player john = new Player();
        Player jayson = new Player();
        coinFlipMatch(john, jayson);
    }
    public void coinFlipMatch(Player p1, Player p2) {
        int coinFlip = (int) (Math.random() * 2 + 1);
        if (coinFlip == 0) {
            p1.addWins();
        } else {
            p2.addWins();
        }
    }
}

So basically, I want player's wins to go up whenever they win a game of coin flip. But I can only do so much because I actually want the number of wins to stay there permanently. Of course, the value for 'int wins' will not stay if I re-run the program or if I delete what is on the main method. But that's exactly why I am here is because of that. I am wondering if such an idea is even possible? How do I make it so that 'int wins' will always be there and not change unless I add more to it?

thank you for reading this rather long (and maybe stupid) question. I would appreciate any help you guys can offer!

Nile
  • 1
  • 1
    You are storing your data _in memory_, ie. it only persists while your program is running. If you wish to persist it beyond a restart, then you must store it externally to your program, eg. in a text file or in a database. – dave Mar 23 '19 at 04:45
  • 1
    then you you need to save your values in a permanent storage like a database or a file, so whenever that values changes in the prograrm you should directly update the database/file. This way you will not lose that values when your program restrart. – guleryuz Mar 23 '19 at 04:49

4 Answers4

2

There can be two ways you can run your program :

  1. Store wins in some external storage.
  2. You can have a command line based while loop which will exit only when you press say 'no'. Otherwise it will again take inputs. Here you can store the wins in memory.
1

Hello and welcome to Stack Overflow!

As you've noticed, after a program has finished execution, it is purged from memory and all non-saved data is lost.

Why is this?

A computer only has so much memory, and clearing unneeded memory allows RAM to be freed and reallocated to new processes, keeping your computer running smoothly.

Okay, so how I save data and use it when my program has started, stopped, and restarted?

If you want some data to persist (be stored and recalled) across multiple executions of a program, you need to save it in some way. There are lots of ways to save data; you can save it to the local filesystem, to a database, send it to an API to be saved by another system, etc.

With this in mind, take some time and consider how and where you want the data to be saved. Your chosen approach should make sense given the requirements of the system. For example, if you are building a program for systems that are not connected to the internet, using an API wouldn't be a good choice.

Once you decide, add a comment to let me know your method of choice, and I can show you how to save the data given your chosen method.

0

Your data is stored in memory. After the run of your main() method completes your program ends and the data is lost. To persist the data you will have to prevent the program from ending.

A while loop is an option to prevent the program from ending.

Example:

import java.util.Scanner;

public class Player {
    private int wins;

    public Player {
        wins = 0; 
    }

    public getWins() {
        return wins;
    }

    public addWins() {
        this.win++;
    } 
}

public class Game {

    public static void main(String[] args) {
        Player john = new Player();
        Player jayson = new Player();

        Scanner sc = new Scanner(System.in); 
        do{ 
           coinFlipMatch(john, jayson); 
           System.out.println("Press 1 to continue");
        }while(sc.nextInt()==1);

        // Here you can write the logic to which one of the players out of 2 won
    }
    public void coinFlipMatch(Player p1, Player p2) {
        int coinFlip = (int) (Math.random() * 2 + 1);
        if (coinFlip == 0) {
            p1.addWins();
        } else {
            p2.addWins();
        }
    } }

Another option is to store your data in some external storage such as a database.

skomisa
  • 16,436
  • 7
  • 61
  • 102
abj1305
  • 635
  • 9
  • 21
0

As already stated by others, the data can be saved in an external file or Database. If its going to be a standalone program, you can save the data in a file per player on the basis of name using Java serialisation/de-serialization. In this way, you can just keep on running the program again and again. It can be modified to take player names as arguments so that you can run the program for different players each time. Here is your updated code using the same:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

class Player implements java.io.Serializable {

    private int wins;
    private String name;

    public Player(String name) {
        this.wins = 0;
        this.name = name;
    }

    public int getWins() {
        return wins;
    }

    public void addWins() {
        this.wins++;
    }

    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return "Name: " + this.getName() + "; Wins: " + this.getWins();
    }
}

public class Game {

    public static void main(String[] args) {
        Player john = deserializePlayer("john");
        if (john==null) {
            john = new Player("john");
        }

        Player jayson = deserializePlayer("jayson");
        if (jayson==null) {
            jayson = new Player("jayson");
        }

        coinFlipMatch(john, jayson);
        serializePlayer(john);
        serializePlayer(jayson);
    }

    public static void coinFlipMatch(Player p1, Player p2) {
        double random = Math.random();
        System.out.println("Random: " + random);
        int coinFlip = (int) (random * 2 );
        System.out.println("coinFlip " + coinFlip);
        if (coinFlip == 0) {
            p1.addWins();
        } else {
            p2.addWins();
        }
    } 

    public static void serializePlayer(Player object) {
        // Serialization
        try
        {
            //Saving of object in a file
            FileOutputStream file = new FileOutputStream(object.getName());
            ObjectOutputStream out = new ObjectOutputStream(file);

            // Method for serialization of object
            out.writeObject(object);

            out.close();
            file.close();

            System.out.println(object.toString());
        }
        catch(IOException ex)
        {
            System.out.println("IOException is caught");
        }
    }

    public static Player deserializePlayer(String filename) {
        Player player = null;
        try
        {
            File f = new File(filename);
            if(f.exists() ) {
                // Reading the object from a file
                FileInputStream file = new FileInputStream(filename);
                ObjectInputStream in = new ObjectInputStream(file);

                // Method for deserialization of object
                player = (Player) in.readObject();

                in.close();
                file.close();

                System.out.println(player.toString());
            } else {
                System.out.println("Player " + filename +  " doesnt exist");
            }
        }
        catch(IOException ex)
        {
            System.out.println("IOException is caught");
        }
        catch(ClassNotFoundException ex)
        {
            System.out.println("ClassNotFoundException is caught");
        }
        return player;
    }
}
deepak
  • 113
  • 8