Я не знаю, почему я получаю NPE, консультируясь, если позиция 2darray объектов (ячеек) пуста или нет. Я проверяю это на if ((matrix[i][j]) == null)
, и я пробовал if ((matrix[i][j]) != null)
, но я получаю NPE снова и снова. Я хочу знать, как я проверить это без того NPE ...Почему я получаю NullPointerException в этом конкретном случае?
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);
}
матрица получила инициализацию ...
Вы можете скомпилировать свой код? Каково определение класса Cell/Position? – SMA
Вы можете скомпилировать код, поскольку я не думаю, что Java разрешает имена классов начинать с числового символа, который конфликтует с именем класса 2darrayofcells, а также ваш конструктор (public 2darrayofcell (Position pos)) имеет недопустимую подпись, возможно, вы пропустили ' в конце имени. – Himanshu
@almasshaikh Код компилируется, проблема возникает при попытке функционала. Ячейка содержит 2 ints. – Jan