I am making a 3x3 grid type application, and I want to recall the button pressed to change it by adding a for loop. However, I get the exception "java.lang.ArrayIndexOutOfBoundsException: length=3; index=3" because the for loop is weird. Could anyone figure out this for me? I am new to java and programming in general.
Code:
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);
}
});
}
}