其他类中的java调用方法并不识别已更改的变量

时间:2016-10-25 16:04:44

标签: java class methods

我正在开发一个简单的基于文本的RPG游戏。目前我正在开发一个系统,用于将播放器的进度保存到可以重新打开和加载的文本文件中。这是我遇到问题的地方。当调用一个返回类中单个变量值的getter时,getter返回我设置的默认值0,并且不会识别我在整个游戏中更改了它的值。

角色等级

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; }
}

如果我在主游戏中创建一个Character变量,并使用代码

为一个值赋值
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.
}

如果我去其他没有主要功能的班级,例如:

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()));
    }
}

我应该能够使用main函数返回那个类并说:

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
}

并打印相同的值5.但是,它打印出在字符类中初始化强度变量时分配的值0。如果我在字符类中更改了strength的默认值,如下所示:

public class Character
{ private int _strength = 5; //initialize the strength variable }

然后主类中的save.saveGame方法将打印出来5.我已经被困在这几天了,尽管我付出了努力,谷歌仍然没有任何帮助。

2 个答案:

答案 0 :(得分:1)

您的问题是,在创建保存对象时创建新角色,而不是传入要保存的角色。您可以尝试这样的事情:

public class SaveSystem
{
    public SaveSystem()
    {  }

    public void saveGame(Character character)
    {
        //just to test the methods used earlier
        System.out.println(character.getStrength()));
    }
}

然后你将它称为:

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(character); //containing nothing but the character.getStrength() method
}

答案 1 :(得分:1)

您的SaveSystem应该保存现有的Character个对象,而不是单独创建全新的对象并保存它们。

请删除SaveSystem中的创建内容,并将Character传递给保存方法。

public class SaveSystem
{


    public SaveSystem()
    {  }

    public void saveGame(Character character)
    {
        //just to test the methods used earlier
        System.out.println(character.getStrength()));
    }
}

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(character); 
}
相关问题