0

我正在为 Android 制作数独游戏,但我遇到了问题。游戏可以编译,但是一旦您进入游戏屏幕并按下按钮,游戏就会崩溃。

我检查了logcat,这些似乎是错误:

05-04 09:07:41.620: ERROR/AndroidRuntime(325): FATAL EXCEPTION: main
05-04 09:07:41.620: ERROR/AndroidRuntime(325): java.lang.ArrayIndexOutOfBoundsException
05-04 09:07:41.620: ERROR/AndroidRuntime(325):     at org.example.fpsudoku.Button.findScreenV(Button.java:59)
05-04 09:07:41.620: ERROR/AndroidRuntime(325):     at org.example.fpsudoku.Button.onCreate(Button.java:38)
05-04 09:07:41.620: ERROR/AndroidRuntime(325):     at android.app.Dialog.dispatchOnCreate(Dialog.java:307)
05-04 09:07:41.620: ERROR/AndroidRuntime(325):     at android.app.Dialog.show(Dialog.java:225)
05-04 09:07:41.620: ERROR/AndroidRuntime(325):     at org.example.fpsudoku.Game.showButtonOrError(Game.java:181)
05-04 09:07:41.620: ERROR/AndroidRuntime(325):     at org.example.fpsudoku.SudokuScreen.onTouchEvent(SudokuScreen.java:221)
05-04 09:07:41.620: ERROR/AndroidRuntime(325):     at android.view.View.dispatchTouchEvent(View.java:3766)

这似乎是问题的代码:

    findScreenV();

    for (int element : usesquare)
    {
        if (element != 0)
            buttons[element - 1].setVisibility(View.INVISIBLE);
    }
    setListeners();
}

private void findScreenV()
{
    button = findViewById(R.id.button);
    buttons[1] = findViewById(R.id.button_1);
    buttons[2] = findViewById(R.id.button_2);
    buttons[3] = findViewById(R.id.button_3);
    buttons[4] = findViewById(R.id.button_4);
    buttons[5] = findViewById(R.id.button_5);
    buttons[6] = findViewById(R.id.button_6);
    buttons[7] = findViewById(R.id.button_7);
    buttons[8] = findViewById(R.id.button_8);
    buttons[9] = findViewById(R.id.button_9);
4

3 回答 3

8

只是一个猜测 - 数组索引是从零开始的。如果你需要 9 个按钮,你会做

Button[] buttons = new Button[9];

创建数组和

button = findViewById(R.id.button);
buttons[0] = findViewById(R.id.button_1);
buttons[1] = findViewById(R.id.button_2);
buttons[2] = findViewById(R.id.button_3);
buttons[3] = findViewById(R.id.button_4);
buttons[4] = findViewById(R.id.button_5);
buttons[5] = findViewById(R.id.button_6);
buttons[6] = findViewById(R.id.button_7);
buttons[7] = findViewById(R.id.button_8);
buttons[8] = findViewById(R.id.button_9);

填充它。buttons[9]在我的示例中寻址肯定会创建一个ArrayIndexOutOfBoundsException

于 2011-05-04T09:20:27.257 回答
1

如果数组的长度为 9,则意味着您可以将 arr[0] 检索到 arr[8],如果您尝试检索不存在的 arr[9],您将收到 ArrayIndexOutOfBoundsException。

于 2011-05-04T12:23:14.410 回答
0

在 Java 中,当您创建数组时,您需要给出该数组的固定大小。像 Button[] buttons = new Button[9] 然后创建该数组的对象,如 buttons[0] = findViewById(R.id.button_1); 其他明智的使用 arrayList 作为最佳解决方案。

于 2011-05-04T09:50:08.627 回答