時,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
}
}
你能發佈'遊戲類嗎? – nachokk
我們需要更多的代碼,特別是類遊戲的構造函數和創建實例和調用方法的順序,直到pickPlayers – libik
發佈整個類 – kylecblyth