I am working on developing a simple text-based RPG game. Currently I am working on a system to save the player's progress to a text file that can be reopened and loaded from. This is where I encountered my problem. When calling a getter that returns the value of a single variable in a class, the getter returns the default value of 0 that I have set and doesn't recognize that I changed the value of it throughout the game.
Character Class
public class Character
{
private int _strength = 0; //initialize the strength variable
public Character() //constructor
{ }
public void setStrength(int strength) //sets the value of strength
{ _strength = strength; }
public int getStrength() //gets the value of strength
{ return _strength; }
}
If I create a Character variable in the main game and assign strength a value with the code:
public static void main(String[] args)
{
Character character = new Character(); //initializes the Character variable
character.setStrength(5); //sets the character's strength to 5
System.out.println(character.getStrength()); //prints out 5 as expected.
}
If I go to a different class without the main function in it, such as:
public class SaveSystem
{
private Character character = new Character(); //exactly the same as above...
public SaveSystem()
{ }
public void saveGame()
{
//just to test the methods used earlier
System.out.println(character.getStrength()));
}
}
I should be able to go back to that class with the main function and say:
public static void main(String[] args)
{
Character character = new Character(); //initializes the Character variable
SaveSystem save = new SaveSystem();
character.setStrength(5); //sets the character's strength to 5
save.saveGame(); //containing nothing but the character.getStrength() method
}
and have it print the same value of 5. However, it prints out the value of 0 that is assigned when the strength variable is initialized in the character class. If I change the default value of strength in the character class as shown:
public class Character
{ private int _strength = 5; //initialize the strength variable }
then the save.saveGame method in the main class will print out 5. I have been stuck on this for a few days now, and Google has not been helpful in the slightest despite my efforts.