java 2d数组没有正确填充
问题描述:
概述: 我有一个“节点”的二维数组,它是一个简单的对象,我有一个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)
答
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
值执行操作时抛出该错误。
+0
非常感谢你。完美的作品 – joey101937
答
填充节点正确
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...");
}
}
你能告诉我们的错误消息,从控制台得到什么? –
你正在迭代我和w,但你总是分配给同一个节点(nodes [x] [y]应该是nodes [i] [w]?) – HomeIsWhereThePcIs