I know this type of question has been asked before, but in my case my code is different and I have no idea where this NullPointer is coming from.
I am recreating Conway's Game of Life using GridWorld, and I am getting this NullPointerException. I have no clue where it is coming from because looking at the code, it should be working. The act method of this code runs every time GridWorld moves forward a "step". In the first step, the cells are removed and born fine. However, when the second iteration comes, there is a NullPointerException when I try to remove a cell from the grid, when there is a cell there.
int count=0;
public void act() {
if (!isDying) {
count++;
for (Location loc : this.getGrid().getOccupiedLocations()) {
int nCount = this.getGrid().getOccupiedAdjacentLocations(loc).size();
if (nCount == 2 || nCount == 3) {
//Do nothing
} else if (nCount == 1 || nCount == 0) {
//Die of loneliness
if(!deathRow.contains(loc)) {
deathRow.add(loc);
}
} else if(nCount>=4) {
//Die of overcrowding
if(!deathRow.contains(loc)) {
deathRow.add(loc);
}
}
candidateNeighbors = this.getGrid().getEmptyAdjacentLocations(loc);
for (Location candidate : candidateNeighbors) {
int cCount = this.getGrid().getOccupiedAdjacentLocations(candidate).size();
if(cCount==3){
if(!birthList.contains(candidate)) {
birthList.add(candidate);
}
}
}
}
isDying=true;
}
else{
count++;
System.out.println("\nAct: "+count);
if(deathRow.size()!=0) {
for (Location death : deathRow) {
System.out.println("Death List: "+deathRow);
System.out.println("Cell to Die: "+death);
this.getGrid().get(death).removeSelfFromGrid();
}
deathRow.clear();
}
if(birthList.size()!=0) {
for (Location birth : birthList) {
System.out.println("Birth List: "+birthList);
System.out.println("Cell to be born: "+birth);
Cell newCell = new Cell();
newCell.putSelfInGrid(this.getGrid(), birth);
}
birthList.clear();
}
isDying=false;
}
}
When I run the code, this is my console output:
Act: 2
Death List: [(9, 10), (11, 10)]
Cell to Die: (9, 10)
Death List: [(9, 10), (11, 10)]
Cell to Die: (11, 10)
Birth List: [(10, 11), (10, 9)]
Cell to be born: (10, 11)
Birth List: [(10, 11), (10, 9)]
Cell to be born: (10, 9)
Act: 2
Death List: [(10, 9), (10, 11)]
Cell to Die: (10, 9)
Death List: [(10, 9), (10, 11)]
Cell to Die: (10, 11)
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at apcs.life.Cell.act(Cell.java:54)
Line 54 is this.getGrid().get(death).removeSelfFromGrid();
Thank you for your guys' help!