NullPointerException找不到错误

时间:2013-12-15 06:55:35

标签: java nullpointerexception dijkstra

无法找到我收到此NullPointException的原因。它指向2个特定的行。

这是错误:

Exception in thread "main" java.lang.NullPointerException
at Railroad.dijkstra(Railroad.java:52)
at Railroad.main(Railroad.java:36)

这两行:

dijkstra(A);

for (Edge x : w.edges){

为方便起见,这是整个代码:

发布整个代码,以便更容易理解我来自哪里。希望它会有所帮助,谢谢!

    Vertex[] vertices = { A, B, C, D, E, F, G, H, I, J, K, L, M };
    dijkstra(A);
    for (Vertex v : vertices)
{
    System.out.println("Distance to " + v + ": " + v.shortestDist);
    List<Vertex> trip = cheapestTrip(v);
    System.out.println("Path: " + trip);
}
}

public static void dijkstra(Vertex s){
    s.shortestDist = 0;
    PriorityQueue<Vertex> cityQueue = new PriorityQueue<Vertex>();
    cityQueue.add(s);

    while(!cityQueue.isEmpty()){
        Vertex w = cityQueue.poll();
        for (Edge x : w.edges){
            Vertex v = x.city;
            int price = x.price;
            int priceOfTrip = w.shortestDist + price;
            if(priceOfTrip < v.shortestDist){   //relaxes the edge that it's on
                cityQueue.remove(v);
                v.shortestDist = priceOfTrip;
                v.prev = w;
                cityQueue.add(v);
            }
        }
    }

}

1 个答案:

答案 0 :(得分:1)

您收到NullPointerException,因为edges对象上的Vertex字段未正确初始化。通常最好使用private字段和getter;这可能会引发有关潜在问题的警告。

Vertex课程中,您应初始化edges。由于您尚未发布代码,因此我们不知道它是什么类型,但如果它是Set,您会说:

Set<Edge> edges = Collections.emptySet(); // if you are going to replace edges
Set<Edge> edges = new HashSet<>();        // if you are going to use edges.add()

修改: edges是一个数组。同样的原则适用;您没有在任何地方设置edges变量,因此默认为null

是一个可以防止直接问题的默认设置
Edge[] edges = new Edge[0];

但你最好重构一个集合类型,它可以让你添加任意数量的边,最好还是重构一下,以便在不同的类中强制执行字段封装。

编辑2:具体问题在于K(DC)和M(NY)。您在其他城市设置edges字段,但不在其他城市设置。