I am writing a custom Rock in GridWorld. However when, I run the following code:
for(int i = 0;i<7;i++){
Grid<Actor> g = getGrid();
Location l = getLocation();
int x = l.getCol();
int y = l.getRow();
switch(i){
case 0:
Location l1 = new Location(x-1,y-1);
Actor a = g.get(l1);
if((a.toString()).equals("Infectious Rock")){
}else if((a.toString()).equals("Infectious Bug")){
}else{
a.removeSelfFromGrid();
}
break;
(This is repeated 7 more times with different variables and different coordinates)
Here is the NPE:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at infectiousRock.act(infectiousRock.java:18)
Does anyone know what is causing this?
You first have to check if the Actor you get from calling g.get(1l)
exists or not. There is a simple fix to this, change your current if statement to:
if(a != null) {
if((a.toString()).equals("Infectious Rock")){
}else if((a.toString()).equals("Infectious Bug")){
}else{
a.removeSelfFromGrid();
}
} else
break;
Adding the extra !=null
check should do the trick, and if not leave a comment and I'll do my best to update the answer.