Java没有初始化类,返回null异常错误

时间:2014-11-09 19:23:49

标签: java

在函数中使用类联结时遇到令人沮丧的null异常错误。该类应该初始化,所以这不应该是一个问题。帮助; _;

class RobotData {
class Junction {
    public int juncX;
    public int juncY;
    public int arrivalHeading;
}

private static int maxJunctions = 10000; //Max junctions likely to occur
private static int junctionCounter;
private static Junction[] junction;

RobotData() {
    junctionCounter = 0;
    junction = new Junction[maxJunctions];
}

public void resetJunctionCounter() { junctionCounter = 0; }

public void recordJunction(IRobot robot) {
    junction[junctionCounter].juncX = robot.getLocation().x;
    junction[junctionCounter].juncY = robot.getLocation().y;
    junction[junctionCounter].arrivalHeading = robot.getHeading();
    junctionCounter++;
}

public void  printJunction() {
    System.out.println(junction[junctionCounter].juncX);
    System.out.println(junction[junctionCounter].juncY);
    System.out.println(junction[junctionCounter].arrivalHeading);
}
}

类RobotData正在初始化,但是当调用函数时,我得到null错误,表明联接[junctionCounter]尚未初始化。不确定为什么(显然),因为它应该在RobotData时初始化。

1 个答案:

答案 0 :(得分:3)

当你写这一行时:

junction = new Junction[maxJunctions];

您可以在堆上创建一个对Junction个实例的maxJunctions引用数组。所有这些都是null,直到您通过调用new将它们指向堆上的对象。

这是另一个想法:

public class Junction {
    public final int juncX;
    public final int juncY;
    public final int arrivalHeading;

    public String toString() {
        return String.format("x = %d y = %d arrivalHeader = %d", juncX, juncY, arrivalHeading);
    }
}

public class RobotData {

    private List<Junction> junctions;

    RobotData() {
        this.junctions = new ArrayList<Junction>();
    }

    public void recordJunction(IRobot robot) {
        Junction junction = new Junction();    
        junction.juncX = robot.getLocation().x;
        junction.juncY = robot.getLocation().y;
        junction.arrivalHeading = robot.getHeading();
        junctions.add(junction);
    }
}