概述: 我有一個「節點」的二維數組,它是一個簡單的對象,我有一個x和y座標並存儲一些基本值。java 2d數組沒有正確填充
網格是一個類,它將所有節點保存在其二維節點數組「節點」中。網格構造函數需要兩個參數:寬度和高度(x & y),然後使用座標(字段)與二維數組中的座標相匹配的節點填充二維數組,除了這樣做以外。出於某種原因,該陣列空物體填滿,並拋出一個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();
}
}
}
}
編輯 - 這裏是打印出來。 遊戲是爲其網格調用「更新」方法的類。
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)
你能告訴我們的錯誤消息,從控制檯得到什麼? –
你正在迭代我和w,但你總是分配給同一個節點(nodes [x] [y]應該是nodes [i] [w]?) – HomeIsWhereThePcIs