Java 为什么在这种特殊情况下我会得到NullPointerException?
我不知道为什么我会在咨询时得到一个NPE,如果一个二维数组的一个位置是空的还是空的。我通过if矩阵[i][j]==null来检查这一点,我已经尝试了if矩阵[i][j]!=空,但我得到的NPE一次又一次。我想知道在没有NPE的情况下如何检查它Java 为什么在这种特殊情况下我会得到NullPointerException?,java,pointers,exception,matrix,null,Java,Pointers,Exception,Matrix,Null,我不知道为什么我会在咨询时得到一个NPE,如果一个二维数组的一个位置是空的还是空的。我通过if矩阵[i][j]==null来检查这一点,我已经尝试了if矩阵[i][j]!=空,但我得到的NPE一次又一次。我想知道在没有NPE的情况下如何检查它 public class 2darrayofcells { //rows and columns are final by requirement private final int rows; private final int colums; pr
public class 2darrayofcells {
//rows and columns are final by requirement
private final int rows;
private final int colums;
private Cell[][] matrix;
//the array needs an initial object
private Cell initialCell;
//Position class consist on 2 integers (x,y)
public 2darrayofcell(Position pos){
//the arg pos is used to create the initial cell in the specified position of the array
rows = 10;
columns = 10;
matrix = new Cell[rows][columns];
initialCell = new Cell();
matrix[pos.getX()][pos.getY()] = initialCell;
}
. . .
//Here i put a cell in a position of the array but before putting it
//i need to know if it's empty. It will return true if the cell is added to
//that position
public boolean putCell(Cell cell, Position pos){
//Null Pointer Exception
if (matrix[pos.getX()][pos.getY()] == null) {
//Do stuff
return true;
}
return false;
}
}
主课
public static void main(String[] args) {
Position pos = new Position(5,5);
2darrayofcells test = new 2darrayofcells(pos);
//test only has an object in 5,5
//The position for the cell i want to insert (3,3) is empty
Position cellPos = new Position(3,3);
Cell testCell = new Cell();
test.putCell(testCell, cellpos);
}
矩阵得到了初始化…在您对putCell的调用中,您不想将cellPos作为第二个参数传递吗?关于NPE,这一行有三种可能的解释:
if (matrix[pos.getX()][pos.getY()] == null) {
说明1:矩阵为空
说明2:pos为空
说明3:矩阵[pos.getX]为空
不可能找出这些解释中哪一个是正确的。基本上,代码片段是不一致的,也就是说,它们不会编译,而这些不一致性使我们无法了解真实代码中发生了什么
即使忽略编译错误,代码的不同部分似乎也暗示没有一个解释是正确的。然而,这不可能是真的。如果正是上面这一行抛出了一个NPE,那么除了上面这三个,没有其他可能的解释了。无。我不知道单元格是什么样子,但您可能尝试在默认值为null的单元格上使用getter:
if (matrix[pos.getX()][pos.getY()] == null)
pos.getX() throws NullPointerException
尝试:
if (matrix[0][0] == null) {
它能工作吗?您能编译代码吗?Cell/Position类的定义是什么?你能编译代码吗?因为我认为Java不允许类名以数字字符开头,而数字字符与2darayofcells类名冲突,而且你的构造函数public 2darayofcellposition pos的签名无效,可能您在名称的末尾漏掉了一个“s”。@almasshaikh代码编译时,问题是在尝试函数性时出现的。单元格包含2个整数。@Himanshu我知道,但那不是类的真实名称。是的,我忘了写它。现在编辑,真奇怪。默认情况下,矩阵的所有元素都为null。矩阵存在…我帮不了你。你问题中的代码显然不是真正的代码。除非你发一个SSCCE,否则我不会给你更多的帮助。无论如何,谢谢。我将再次阅读我的代码,也许我没有看到与这三种解释之一相关的任何问题。正如你所说,我将一个空位置作为第二个参数传递给Putchell。不。。。我不知道是否有必要将异常抛出到工作中