概述:我有一个"节点"的2D数组,这是一个简单的对象,有一个x和y坐标,并存储一些基本值。
Grid是一个类,它在其2D节点数组"nodes"中包含我的所有节点。网格构造函数采用两个参数:宽度和高度(x&y(,然后用坐标(字段(与其在2D阵列中的坐标匹配的节点填充2D阵列。。。。。除非那不会发生。出于某种原因,每当我试图引用时,数组就会填充null对象并抛出NullPointerException
public class Node {
//fields
public int x, y; //coordinates
public int Fcost, Hcost; //values used for pathfinding. f is distance from user, h is distance from target.
public boolean validity = false;
//Constructors
public Node(int x, int y) {
this.x = x;
this.y = y;
}
public Node(int x, int y, int F, int H) {
this.x = x;
this.y = y;
this.Fcost = F;
this.Hcost = H;
}
public Node(Node n) {
this.x = n.x;
this.y = n.y;
this.Fcost = n.Fcost;
this.Hcost = n.Hcost;
}
public boolean isValid() {
////if out of bounds, return flase.
if (this.x >= Game.width) {
return false;
}
if (this.x < 0) {
return false;
}
if (this.y >= Game.height) {
return false;
}
if (this.y < 0) {
return false;
}
return true;
}
public void checkIfValid() {
this.validity = this.isValid();
}
public class Grid {
public Node[][] nodes;
private int length, height;
///constructor
//populates the grid with a new node for each coordinate
public Grid(int x, int y) {
nodes = new Node[x + 1][y + 1];
for (int i = 0; i < x; i++) {
for (int w = 0; w < y; w++) {
nodes[x][y] = new Node(x, y);
System.out.println("populating...");
}
}
this.length = x;
this.height = y;
////prints the number of nodes
int w = 0;
for (Node[] a : nodes) {
for (Node n : a) {
w++;
}
}
System.out.println("nodes " + w);
}
///methods
public Node[] getNeighbors(Node in) {
ArrayList<Node> n = new ArrayList<>();
////NOT YET IMPLEMENTED
return (Node[]) n.toArray();
}
///tells each node to check weather or not it is valid
public void update() {
for (Node n[] : nodes) {
for (Node realNode : n) {
realNode.checkIfValid();
}
}
}
}
编辑-这是打印出来的。Game是为其网格调用"update"方法的类。
java.lang.NullPointerException
at Pathfinding.Grid.update(Grid.java:55)
at pkg2dgame.Game.tick(Game.java:62)
at pkg2dgame.Game.run(Game.java:104)
at java.lang.Thread.run(Thread.java:745)
正确填充节点
for (int i = 0; i < x; i++) {
for (int w = 0; w < y; w++) {
nodes[i][w] = new Node(i, w);
System.out.println("populating...");
}
}
nodes[x][y] = new Node(x, y);
应为nodes[i][w] = new Node(x, y);
您一直在重新填充相同的索引,因此所有数组存储桶都为空。代码的另一个问题是,for循环直到2d数组结束才循环。
for (int i = 0; i < nodes.length; i++) {
for (int w = 0; w < nodes[i].length; w++) {
nodes[i][w] = new Node(x, y);
System.out.println("populating...");
}
}
它在对null
值执行操作时抛出该错误。