java 2d数组没有正确填充

时间:2016-09-22 00:01:27

标签: java arrays multidimensional-array

概述: 我有一个" Nodes"的2D数组,这是一个简单的对象,我有一个x和y坐标,并存储一些基本值。

Grid是一个将所有节点保存在其2D节点数组中的类,"节点"。网格构造函数采用两个参数:宽度和高度(x& y),然后使用节点填充2D数组,这些节点的坐标(字段)与2D数组中的坐标匹配.....除了doest发生。由于某种原因,数组填充空对象并在我尝试重新引用时抛出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();
        }
    }
}

}

编辑 - 打印出来的是什么。 游戏是调用&#34;更新&#34;它的网格方法。

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)

2 个答案:

答案 0 :(得分:2)

正确填充节点

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...");
        }
    }

答案 1 :(得分:1)

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值执行操作时抛出该错误。