我正在为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);
发布于 2011-05-04 17:20:27
只是猜测-数组索引是基于零的。如果你需要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-04 20:23:14
如果数组的长度是9,这意味着你可以检索arr到arr8,如果你试图检索不存在的arr9,你将得到一个ArrayIndexOutOfBoundsException。
发布于 2011-05-04 17:50:09
在Java中创建数组时,需要给出该数组的固定大小。如Button[] buttons = Button9,然后创建该数组的对象,如buttons = findViewById(R.id.button_1);否则使用arrayList作为最佳解决方案。
https://stackoverflow.com/questions/5881162
复制相似问题