我正在这里使用这个类并尝试在其上调用.get()方法。这似乎很简单,但无论我改变什么,我都会在行上得到nullPointerException:
value = gameBoard[row-1][column-1];
似乎它可能是一个错误,但我几乎肯定数组是正确的大小和主方法中的.get方法,它调用它以1行和1列开始,所以我可以我们看错了......
public class Simple2DArray implements Simple2DInterface
{
public int[][] gameBoard;
public Simple2DArray(int aRow, int aColumn)
{
int[][] gameBoard = new int[aRow][aColumn];
for(int i=0;i<aRow;i++)
{
for(int j=0;j<aColumn;j++)
{
gameBoard[i][j] = -1;
}
}
}
public int getNumberOfRows()
{
int rows;
rows = gameBoard.length;
return rows;
}
public int getNumberOfColumns()
{
int columns;
columns = gameBoard[0].length;
return columns;
}
public void clear()
{
for(int i=0;i<gameBoard.length;i++)
{
for(int j=0;j<gameBoard[i].length;i++)
{
gameBoard[i][j] = -1;
}
}
}
public void setToOne(int row, int column)
{
gameBoard[row+1][column+1] = 1;
}
public void setToZero(int row, int column)
{
gameBoard[row+1][column+1] = 0;
}
public void flip(int row, int column)
{
if(gameBoard[row-1][column-1]==1)
{
gameBoard[row-1][column-1]=0;
}
if(gameBoard[row-1][column-1]==0)
{
gameBoard[row-1][column-1]=1;
}
}
public int get(int row, int column)
{
int value;
value = gameBoard[row-1][column-1];
return value;
}
}
答案 0 :(得分:2)
在编写
时,您在构造函数中声明了一个新变量int[][] gameBoard = new int[aRow][aColumn];
删除声明int [] [],它将引用实例变量:
gameBoard = new int[aRow][aColumn];
clear()方法中的内部循环也必须有j ++。