java - 数组初始化作为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;
解决方案
推荐阅读
- reactjs - 更改状态后,内容不会重新渲染
- python - Slack:我可以使用 Python 在 Slack 上以特定用户的身份发帖吗?
- c# - Xamarin 表单列表视图无法使用 MVVM。请我对视图模型执行此操作吗?
- javascript - 为什么我的对象数组不会从饼图数据点中删除?
- firebase - 来自多个集合的 Flutter Firestore 搜索
- c++ - 试图制作哈希表,程序编译但不断崩溃
- sql-server - 想要减少数据库命中
- lua - 在 Lua 中解析 \xNN 格式的十六进制数
- ios - json 响应的 codableKey 中的 keyNotFound
- ssl - 无法创建 SSL/TLS 安全通道仅在 Windows Server 2012 中发生