我正在使用 Dijkstras 算法,但我似乎无法弄清楚为什么我的构造函数不能正常工作。
具体来说这一行:A.edges = new Edge[]{ new Edge(B, 35), new Edge(C, 50)};
给我错误:“错误:类 Edge 中的构造函数 Edge 无法应用于给定类型;”
public static void main(String[]args){
//sets all the cities/nodes to a vertex
Vertex A = new Vertex("CityA");
Vertex B = new Vertex("CityB");
//distance from each city to their new cities
A.edges = new Edge[]{ new Edge(B, 35), new Edge(C, 50)};
}
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);
}
}
}
}
//Contructor
public static class Edge{
public static int price;
public static Vertex city;
public static void Edge(Vertex altCity, int altPrice){
city = altCity;
price = altPrice;
}
}
最佳答案
这一行
public static void Edge(Vertex altCity, int altPrice){
不是构造函数;它是一个返回void
的静态方法。构造函数不是静态
,并且它们不返回任何内容。尝试一下
public Edge(Vertex altCity, int altPrice){
此外,您的 Edge
类的成员变量也不应该是static
:
public int price;
public Vertex city;
关于java - 给定类型的构造函数错误,无法应用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20591572/