找不到出现此 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);
}
}
}
}
最佳答案
您收到 NullPointerException
是因为 Vertex
对象上的 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
是一个数组。同样的原则也适用;您没有在任何地方设置 edges
变量,因此它默认为 null
。可以防止立即出现问题的默认设置是
Edge[] edges = new Edge[0];
但是您最好重构为允许您添加任意数量的边的集合类型,并且最好仍然重构以在不同类之间强制执行字段封装。
编辑 2: 具体问题在于 K
(DC) 和 M
(NY)。您在其他城市上设置了 edges
字段,但在这些城市上没有设置。
关于java - NullPointerException找不到错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20592066/