2016-10-25 96 views
1

我正在開發一個簡單的基於文本的RPG遊戲。目前我正在研究一個系統來將玩家的進度保存到可以重新打開和加載的文本文件中。這是我遇到我的問題的地方。當調用一個返回類中單個變量值的getter時,getter返回我設置的默認值0,並且無法識別我在整個遊戲中改變了它的值。其他類中的java調用方法無法識別已更改的變量

字符類

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

如果我創建主遊戲中的角色變量並使用代碼分配強度值:

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

我應該能夠回到那個類的主要樂趣ction和說:

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。如果我更改字符級實力的默認值,如下所示:

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

然後在主類中的方法save.saveGame會打印出5.我一直停留在這幾天,現在,儘管我付出了努力,谷歌並沒有絲毫幫助。

+2

您可以發佈[MCVE] – khelwood

+1

你們倆都是對的。不過,我不確定哪一個在這裏可以接受。非常感謝你的幫助!我一直堅持這一點! – dragonfyyre

回答

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

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