I am trying to code an implementation of the A* pathfinding algorithm, and, when searching across an array of States, the compiler outputs the error
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "State.toString()" because "nodes[i]" is null at Algorithm.updateGF(Algorithm.java:109) at Algorithm.searchPath(Algorithm.java:27) at Main.main(Main.java:5). This is the subroutine that causes the error
for (int i = 0; i < nodes.length; i++) {
if ((openset.containsKey(nodes[i]) && closedset.get(current) < closedset.get(parentset.get(nodes[i])))
|| (!openset.containsKey(nodes[i]))) {
parentset.put(nodes[i], current);
nodes[i].toString();
openset.put(nodes[i], closedset.get(current) + 1+manhattanDistance(nodes[i],maze.getGoal()));
}
}
}
The same error happens when I try to iterate across a Set<> of States. I have not been able to figure out the cause.
This is the implementation of the State class:
public enum type{BLANK,OBSTACLE,OBJECTIVE,INITIAL,PATH};
private int X,Y;
private type sttype;
public State(int x, int y, double obsfraction) {
X = x;
Y = y;
double gen = genRandom();
if(gen<obsfraction) {
sttype=State.type.OBSTACLE;
}else {
sttype=State.type.BLANK;
}
}
private static double genRandom() {
return Math.random();
}
public int getX() {
return X;
}
public int getY() {
return Y;
}
public type getType() {
return sttype;
}
public void setX(int x) {
X = x;
}
public void setY(int y) {
Y = y;
}
public void setType(type sttype) {
this.sttype = sttype;
}
public char toChar() {
switch (this.getType()) {
case OBSTACLE:
return '*';
case BLANK:
return ' ';
case INITIAL:
return 'I';
case OBJECTIVE:
return 'G';
case PATH:
return '+';
default:
return 'E';
}
}
public String toString() {
return toChar()+": "+getX()+","+getY();
}
}
And this is the initialization of openset, parentset, and closedset:
private static Map<State, Integer> openset = new HashMap<State, Integer>();// Initializes openset as a mapping of
// every
// explored node and its associated g(node)
private static Map<State, Integer> closedset = new HashMap<State, Integer>();// Initializes closedset as a mapping
// of every
// explored node and its associated g(node)
private static Map<State, State> parentset = new HashMap<State, State>();// Initializes parentset as a mapping of
// every
// explored node and its associated parent; that
// is, the node that leads to it, following the
// shortest found path
```