문제

Can't find the reason why I'm getting this NullPointException. It's pointing to 2 specific line.

This is the error:

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

These are the 2 lines:

dijkstra(A);

for (Edge x : w.edges){

This is the whole code for convenience:

Posting the whole code for easier to understand where I'm coming from. Hopefully it'll help, thanks!

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

}
도움이 되었습니까?

해결책

You're getting the NullPointerException because the edges field on your Vertex object isn't getting properly initialized. It's generally best to use private fields and getters; this would have caused warnings about the potential problem.

Inside your Vertex class, you should initialize edges. Since you haven't posted the code, we don't know what type it is, but if it's a Set, for example, you would say:

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()

Edit: edges is an array. The same principle applies; you aren't setting that edges variable anywhere, and so it defaults to null. A default that will prevent the immediate problem is

Edge[] edges = new Edge[0];

but you're better off refactoring to a collection type that will let you add an arbitrary number of edges, and better off still refactoring to enforce field encapsulation among your different classes.

Edit 2: The specific problem is with K (DC) and M (NY). You set the edges field on other cities, but not on those.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top