java 2d数组未正确填充
概述: 我有一个“节点”的2D数组,这是一个简单的对象,它有一个x和y坐标,并存储一些基本值 Grid是一个在其2D节点数组“nodes”中保存所有my节点的类。栅格构造函数接受两个参数:宽度和高度(x&y),然后使用坐标(字段)与其在2D数组中的坐标匹配的节点填充2D数组。。。。。但那不会发生。出于某种原因,每当我尝试引用空对象时,该数组就会填充空对象并抛出java 2d数组未正确填充,java,arrays,multidimensional-array,Java,Arrays,Multidimensional Array,概述: 我有一个“节点”的2D数组,这是一个简单的对象,它有一个x和y坐标,并存储一些基本值 Grid是一个在其2D节点数组“nodes”中保存所有my节点的类。栅格构造函数接受两个参数:宽度和高度(x&y),然后使用坐标(字段)与其在2D数组中的坐标匹配的节点填充2D数组。。。。。但那不会发生。出于某种原因,每当我尝试引用空对象时,该数组就会填充空对象并抛出NullPointerException public class Node { //fields public int 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();
}
节点[x][y]=新节点(x,y)代码>应该是节点[i][w]=新节点(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...");
}
}
for(int i=0;i
它在对null
值执行操作时抛出该错误。正确填充节点
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...");
}
}
for(int i=0;i
您可以向我们显示从控制台收到的错误消息吗?您正在使用i和w进行迭代,但您总是分配给同一个节点(节点[x][y]应该是节点[i][w]?)
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...");
}
}
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...");
}
}