2016-05-23 72 views
2

我面臨靜態數組列表問題。Static ArrayList - 填充增強的循環

我有一個玩家類需要一個字符串。

public Player (String s) {  
    myPlayerName = s; 
    myPlayerScore = 0; 
} 

我有一個靜態的播放列表和一個靜態數組字符串。我有一個填充數組列表的函數。

public void buildPlayerList() {  
    System.out.println("Before - " + MY_PLAYER_LIST.size()); 
    for (String temp: TEST_PLAYER_LIST) { 
     Player tempPlayer = new Player(temp); 
     MY_PLAYER_LIST.add(tempPlayer); 
     System.out.println("Player: " + tempPlayer.getMyPlayerName()); 
    } 
    System.out.println("After - " + MY_PLAYER_LIST.size()); 
    for (Player temp: MY_PLAYER_LIST) {  
     System.out.println(temp.getMyPlayerName());  
    } 
} 

但是,我得到的輸出是;

Before - 0 
Player: adam 
Player: eve 
Player: john 
Player: mary 
After - 4 
Player: mary 
Player: mary 
Player: mary 
Player: mary 

任何人都可以請幫我理解我在做什麼錯了嗎?

+3

'myPlayerName'在'Player'類可能是靜態的。刪除靜態關鍵字。 – Eran

+2

請同時顯示myPlayerName的decleration –

+1

'Player'中的'myPlayerName'不是靜態的嗎? – Serg

回答

5

確保播放器類如下所示:

public class Player{ 
    private String myPlayerName; 
    private int myPlayerScore; 
    public Player (String s) {  
     myPlayerName = s; 
     myPlayerScore = 0; 
    } 
    public String getMyPlayerName() { 
     return myPlayerName; 
    }   
} 
+1

這將工作,因爲它似乎是playerName是靜態的 – Supahupe

+1

這應該是標記正確的答案。 – mubeen

+0

謝謝Safwan - 是的,在玩家課上讓我搞砸了 – Walkerbo