سؤال

I'm using Dijkstras Algorithm and I can't seem to figure out why my constructor isn't working correctly with what I'm trying to do.

Specifically this line: A.edges = new Edge[]{ new Edge(B, 35), new Edge(C, 50)};

Gives me the error: "error: constructor Edge in class Edge cannot be applied to given types;"

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;
    }
}
هل كانت مفيدة؟

المحلول

This line

public static void Edge(Vertex altCity, int altPrice){

is not a constructor; it's a static method that returns void. Constructors aren't static and they don't return anything. Try

public Edge(Vertex altCity, int altPrice){

In addition, your Edge class's member variables shouldn't be static either:

public int price;
public Vertex city;

نصائح أخرى

This is a method syntax :

public static void Edge(Vertex altCity, int altPrice){

This is not a constructor. Your constructor should be like :

public Edge(Vertex altCity, int altPrice){

You can refer here for learning.

Further, your fields are class variables, so every time you call constructor same variables will be set with new values for all objects, not sure if this is what you want.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top