首页 > 解决方案 > 数组初始化作为Java中的实例变量的问题

问题描述

我的问题是,当我试图从我声明为实例变量的数组中获取一些对象时,我得到的是 null 而不是我放入数组中的对象。据我所知,如果我们设置一些默认值,数组应该自动初始化为任何其他实例变量。我将在下面的代码中详细解释它:

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;

标签: javajavafx

解决方案


推荐阅读