2013-12-15 25 views
0

無法找到我得到此NullPointException的原因。它指向2條特定線路。NullPointerException找不到該錯誤

這是錯誤:

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

這些是2行:

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

} 
+0

你可以在代碼中指出Railroad.java:52行嗎? –

+1

@AlexandreLavoie他做到了。 – chrylis

+1

請發佈'Vertex'的代碼。我懷疑有些'Vertex'對象的'edges'字段沒有正確初始化。 – chrylis

回答

1

你讓你的Vertex對象上NullPointerException因爲edges領域是沒有得到正確初始化。通常最好使用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是一個數組。同樣的原則適用;您不在任何地方設置該變量,因此它默認爲null。默認,以防止當前的問題是

Edge[] edges = new Edge[0]; 

,但你最好要重構一個集合類型,可以讓你增加邊緣的任意號碼,最好還是重構執行中的不同領域的封裝類。

編輯2:具體問題是K(DC)和M(NY)。您在其他城市設置了edges字段,但不是這些字段。

+0

我剛剛發佈了我的整個代碼,可能會讓它更清晰。我很確定自己正確地做到了,除非我想我是缺少的東西。 – user2318083

+0

LIFE SAVER,就是這樣!謝謝!! :) 哦,我沒有在M(NY)上設置優勢的原因是因爲那是最後一個節點/城市,所以它沒有一個 – user2318083