我的问题是,当我尝试从声明为实例变量的数组中获取一些对象时,我得到的是空值,而不是放入数组中的对象。据我所知,如果我们将设置一些默认值,则数组应该像其他任何实例变量一样自动初始化。我将在下面的代码中对其进行详细说明:
public class GameBoardAI implements IGameModel{
Random rand = new Random();
int currentPlayer = 1;
TicTacViewController tacController = new TicTacViewController();
Button[] buttonss = new Button[]{ tacController.btn1, tacController.btn2, tacController.btn3, tacController.btn4,
tacController.btn5, tacController.btn6, tacController.btn7, tacController.btn8, tacController.btn9};
这是我课程的开始,这是我尝试使用的方法:
public void switchPlayer() {
if(currentPlayer == 1)
{
currentPlayer=2;
buttonss[rand.nextInt(9)].fire();
}
if(currentPlayer == 2)
currentPlayer = 1;
}
您可以在这里看到,我正在尝试从我在实例变量中创建的按钮数组中获取一些随机按钮。另一个令人困惑的事情是,当我将数组作为方法中的局部变量而不是创建实例变量时,一切工作都很好,如果它对我有帮助,请参见TicTacViewController的代码,按钮位于其中:
public class TicTacViewController implements Initializable
{
@FXML
private Label lblPlayer;
@FXML
private Button btnNewGame;
@FXML
private GridPane gridPane;
private static final String TXT_PLAYER = "Player: ";
private IGameModel game = new GameBoard();
@FXML
public Button btn1;
@FXML
public Button btn2;
@FXML
public Button btn3;
@FXML
public Button btn4;
@FXML
public Button btn5;
@FXML
public Button btn6;
@FXML
public Button btn7;
@FXML
public Button btn8;
@FXML
public Button btn9;