gpt4 book ai didi

java - (Java) 表达式的类型必须是数组类型,但它解析为对象错误

转载 作者:太空宇宙 更新时间:2023-11-04 10:33:48 25 4
gpt4 key购买 nike

以下代码:

// Adds game button container
Object[][] gameButtons = new Object[3][3];

// Adds game buttons to game button container
Arrays.fill(gameButtons, new JButton[3][3]);
for (int i = 0; i < gameButtons.length; i++) {
for (int j = 0; j < gameButtons[i].length; j++) {
for (int k = 0; k < 3; k++) {
for (int l = 0; l < 3; l++) {
gameButtons[i][j][k][l] = new JButton();******
}
}
}
}

向我抛出一个错误:表达式的类型必须是数组类型,但它解析为对象。如何初始化 JButton?

编辑:我忘了澄清。错误发生在 ****** 行 请注意,******** 不在我的代码中。编辑2:我尝试了洛根的修复,但它仍然不起作用:

for (Object[] row : gameButtons)
Arrays.fill(row, new JButton[3][3]);
for (int i = 0; i < gameButtons.length; i++) {
for (int j = 0; j < gameButtons[i].length; j++) {
for (int k = 0; k < 3; k++) {
for (int l = 0; l < 3; l++) {
gameButtons[i][j][k][l] = new JButton();
}
}
}
}

同样的错误,同样的地方。

最佳答案

gameButtons[i][j]Object 类型,无法作为数组进行索引。您必须首先将其转换为 JButton[][] 类型:

for (int i = 0; i < gameButtons.length; i++) {
for (int j = 0; j < gameButtons[i].length; j++) {
// cast it to an array type before accessing
JButton[][] subArray = (JButton[][])(gameButtons[i][j]);

for (int k = 0; k < 3; k++)
for (int l = 0; l < 3; l++)
subArray[k][l] = new JButton();
}
}

关于java - (Java) 表达式的类型必须是数组类型,但它解析为对象错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49700843/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com