Java Array out of bounds错误是不是越界了?
Java Array out of bounds error isn't out of bounds?
这段代码是我程序的相关部分,它会产生一个数组越界错误,我不明白为什么。
我的错误是 'java.lang.ArrayIndexOutOfBoundsException: 6',其中 6 是一个随机值,在 randomShot();
的 if 语句中
public class Ai
{
private int WIDTH;
private int HEIGHT;
public Ai(){
WIDTH=10;
HEIGHT=10;
}
int[][] board=new int[WIDTH][HEIGHT];
Random rand = new Random();
public void randomShot(){
x=rand.nextInt(WIDTH/2);
y=rand.nextInt(HEIGHT);
x=x*2;
if(y%2==0)
{
y+=1;
}
if(board[x][y]!=0) //java.lang.ArrayIndexOutOfBoundsException: 6
{
randomShot();
}
}
我注意到如果我使用代码
int[][] board=new int[10][10];
它工作得很好。我不明白为什么会这样,它在做完全一样的事情吗?
定义板时WIDTH和HEIGHT为0。
在 class 级变量之后调用构造函数。对于 int,默认值为 0.
将 board
初始化移动到构造函数中。字段初始化的顺序意味着在输入构造函数之前声明(并初始化)数组(因此,WIDTH
和 HEIGHT
为零)。
private int WIDTH;
private int HEIGHT;
public Ai(){
WIDTH=10;
HEIGHT=10;
board=new int[WIDTH][HEIGHT]; // <-- here.
}
int[][] board; // =new int[WIDTH][HEIGHT];
这段代码是我程序的相关部分,它会产生一个数组越界错误,我不明白为什么。 我的错误是 'java.lang.ArrayIndexOutOfBoundsException: 6',其中 6 是一个随机值,在 randomShot();
的 if 语句中public class Ai
{
private int WIDTH;
private int HEIGHT;
public Ai(){
WIDTH=10;
HEIGHT=10;
}
int[][] board=new int[WIDTH][HEIGHT];
Random rand = new Random();
public void randomShot(){
x=rand.nextInt(WIDTH/2);
y=rand.nextInt(HEIGHT);
x=x*2;
if(y%2==0)
{
y+=1;
}
if(board[x][y]!=0) //java.lang.ArrayIndexOutOfBoundsException: 6
{
randomShot();
}
}
我注意到如果我使用代码
int[][] board=new int[10][10];
它工作得很好。我不明白为什么会这样,它在做完全一样的事情吗?
定义板时WIDTH和HEIGHT为0。 在 class 级变量之后调用构造函数。对于 int,默认值为 0.
将 board
初始化移动到构造函数中。字段初始化的顺序意味着在输入构造函数之前声明(并初始化)数组(因此,WIDTH
和 HEIGHT
为零)。
private int WIDTH;
private int HEIGHT;
public Ai(){
WIDTH=10;
HEIGHT=10;
board=new int[WIDTH][HEIGHT]; // <-- here.
}
int[][] board; // =new int[WIDTH][HEIGHT];