gpt4 book ai didi

java - 安卓/Java : For loop preventing array from being called

转载 作者:行者123 更新时间:2023-12-01 18:19:46 26 4
gpt4 key购买 nike

我正在制作一个 3x3 网格类型的应用程序,我想通过添加 for 循环来调用按下的按钮来更改它。但是,我收到异常“java.lang.ArrayIndexOutOfBoundsException:length = 3;index = 3”,因为for循环很奇怪。有人能为我解决这个问题吗?我对 Java 和一般编程都很陌生。

代码:

public int j = 1;
public int i = 1;
public final int[][] buttons = new int[][] {
{R.id.top_left_button, R.id.top_center_button, R.id.top_right_button},
{R.id.left_button, R.id.center_button, R.id.right_button},
{R.id.bottom_left_button, R.id.bottom_center_button, R.id.bottom_right_button}};
private Button lastButton;

public void setPlayer(Button button, int x, int y){
button.setText("!");
lastButton = (Button)findViewById(buttons[x][y]);
lastButton.setText(" ");
lastButton = button;
}
@Override


protected void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);


ctx = this;

final GameEngine game = new GameEngine();
lastButton = (Button)findViewById(R.id.center_button);
for (i = 0; i < buttons.length; i++) {
for (j = 0; j < buttons[i].length; j++) {
final Button button = (Button)findViewById(buttons[i][j]);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Button b = (Button)v;
int x = i;
int y = j;
setPlayer(b, x , y);
}
});
}
}

最佳答案

您需要问的问题是: i 的值是多少?和j 点击按钮时

i 的答案是:buttons.length.因为那是你留下的值i当你离开循环时。

这应该有效:

for (i = 0; i < buttons.length; i++) {
final int iCopy = i;
for (j = 0; j < buttons[i].length; j++) {
final Button button = (Button)findViewById(buttons[i][j]);
final int jCopy = j;
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Button b = (Button)v;
int x = iCopy;
int y = jCopy;
setPlayer(b, x , y);
}
});
}
}

这有效的原因是,由于范围的原因,您正在创建 iCopy 的新实例。每次外部迭代,以及 jCopy 的新实例每次内部迭代。每个匿名OnClickListener现在将使用适当的副本来实现。

关于java - 安卓/Java : For loop preventing array from being called,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27956399/

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