2014-02-26 30 views
0

時,java子類的狀態不會改變我有一個叫做Game的超類,它有一個函數pickPlayers()和一個ArrayList<Player> players,它包含被選擇的函數以及擴展它的子類ConsoleGame。問題是當我製作一個ConsoleGame實例並調用myInstance.pickPlayers()時,該實例的數組列表播放器爲空。有任何想法嗎?我想這主要是一個概念上的問題,但如果有幫助,這裏的一些代碼:當我調用函數

下面是類遊戲:

import java.util.ArrayList; 

public abstract class Game { 
    protected String name; 
    protected int numPlayers; 
    protected ArrayList<Player> players; 

    public Game(String n, int np) { 
     name = n; 
     numPlayers = np; 
    } 

    protected void pickPlayers(ArrayList<Player> players) { 
     /** 
     * Choose players at random from the array passed in to play the game 
     * Parameters: 
     *  ArrayList<Player> players - the array of players 
     * Returns: 
     *  void 
     */ 
     // choose players at random from players to play the game 
     for(int j = 0; j < numPlayers; j++) { 
      players.add(players.get(GameNight.generator.nextInt(players.size() - 1))); 
     } 
    } 

    protected abstract void play(); 
} 

和這裏的子類棋盤遊戲:

public class BoardGame extends Game { 

    /** 
    * Luck factor of the game 
    */ 
    private double luckFactor; 

    /** 
    * Constructor, takes three args to set the instance variables 
    * @param n Name of the game 
    * @param np Number of players that can play the game at once 
    * @param l Luck factor 
    */ 
    public BoardGame(String n, int np, double l) { 
     super(n,np); 
     luckFactor = l; 
    } 

    /** 
    * Plays the game and chooses a winner. Winner is chosen to be 
    * the person with the largest value of 
    * intelligence + (luck * luckFactor), where luck refer's to the 
    * Player's luckiness and luckFactor refers to the Game's instance 
    * variable. This method returns nothing but does call youWin() 
    * on the Player that won the game. 
    */ 
    public void play() { 
     // code here 
    } 
} 
+0

你能發佈'遊戲類嗎? – nachokk

+0

我們需要更多的代碼,特別是類遊戲的構造函數和創建實例和調用方法的順序,直到pickPlayers – libik

+0

發佈整個類 – kylecblyth

回答

2
public void pickPlayers(ArrayList<Player> players) {   
    players.get(..) 
} 

它是引用到本地變量,你是shadowing你的實例變量。爲了使用實例屬性,你必須參考this 然後它會。

this.players.get(..) 

注意

通過在創建一個遊戲類型players是空的方式。可能是你應該初始化爲一個空列表。

+0

+1 - 事實上,現在我們看到了他的代碼,這正是他正在做的! –

+0

哈哈初始化空列表結束了這樣做。感謝:D! – kylecblyth

+0

@StephenC OP給了我一個很好的提示'..實例的數組列表玩家是空的..'現在他發佈代碼,以便編輯代碼,感謝upvoting – nachokk

相關問題