TheMiamest TheMiamest - 19 days ago 9
Java Question

Confusing array out of bounds on game board

This is a method in a code for a slightly more complex type of tic tac toe. The problem is, whenever the computer tries to make a move, it gives an array out of bounds -1 error, which is really confusing me because I made sure to specify in the code that it won't do that.

public void computerMove()
{
boolean moveMade=false;
while(!moveMade)
{
int i = (int)(Math.random()*5);
int j = (int)(Math.random()*4);
int p = (int)(Math.random()*5+1);
//whether the piece will move up, down, left or right
if (grid[i][j].getText().equals("0")){
if (p==1&&grid[i+1][j].getText().equals("")
&&i<3&&moveMade==false)
//here i specify when i<3 to make sure it wont try to go off the board
{
grid[i][j].setText("");
grid[i+1][j].setText("0");
turn++; checkXHorizontal(); check0Horizontal();
checkXVertical(); check0Vertical(); checkXDF();
check0DF(); checkXDB(); check0DB();
whoseTurn.setText("Player's Turn");
moveMade=true;
}
else if (p==2&&grid[i][j+1].getText().equals("")
&&j<3&&moveMade==false)
{
grid[i][j].setText("");
grid[i][j+1].setText("0");
turn++; checkXHorizontal(); check0Horizontal();
checkXVertical(); check0Vertical(); checkXDF();
check0DF(); checkXDB(); check0DB();
whoseTurn.setText("Player's Turn");
moveMade=true;
}
else if (p==3&&grid[i][j-1].getText().equals(""
)&&j>0&&moveMade==false)
{
grid[i][j].setText("");
grid[i][j-1].setText("0");
turn++; checkXHorizontal(); check0Horizontal();
checkXVertical(); check0Vertical(); checkXDF();
check0DF(); checkXDB(); check0DB();
whoseTurn.setText("Player's Turn");
moveMade=true;
}
else if (p==4&&grid[i-1][j].getText().equals("")&&
i>1&&moveMade==false)
{
grid[i][j].setText("");
grid[i-1][j].setText("0");
turn++; checkXHorizontal(); check0Horizontal();
checkXVertical(); check0Vertical(); checkXDF();
check0DF(); checkXDB(); check0DB();
whoseTurn.setText("Player's Turn");
moveMade=true;
}
else {
computerMove();
}
}
}

Answer

When you do

 else if (p==3&&grid[i][j-1].getText().equals(""
             )&&j>0&&moveMade==false)

and

else if (p==4&&grid[i-1][j].getText().equals("")&&
             i>1&&moveMade==false)

grid[i][j-1] and grid[i-1][j]could be out of range because java tests them before j>0 and i>1 respectively.

try to move them at the beginning of the if clause, in this way

else if (p==3&&j>0&&grid[i][j-1].getText().equals(""
                 )&&moveMade==false)

and

else if (p==4&&i>1&&grid[i-1][j].getText().equals("")&&moveMade==false)
Comments