David Rolfe
David Rolfe

Reputation: 163

Variable might not have been initialized (edge weighted graph)

So I'm trying to make a program that finds the MST. To build the graph I'm using a bag of edges and I'm reading the graph from a file using this code:

import edu.princeton.cs.algs4.*;

class MyEdgeWeightedGraph {
    private final int V;
    private final int E;
    private Bag<MyEdge> edges;

    public int V() {
        return V;
    }
    public int E() {
        return E;
    }

    public Iterable<MyEdge> edges() { 
        return edges; 
    }

    public MyEdgeWeightedGraph(In in) {
        int E = in.readInt();
        int V = in.readInt();
        if (E < 0) {
            throw new IllegalArgumentException("Number of edges must be nonnegative");
        }
        for (int i = 0; i < E; i++){
            int v = in.readInt();
            int w = in.readInt();
            long weight = in.readLong();
            MyEdge e = new MyEdge(v, w, weight);
            edges.add(e);
        }
    }
}

Because I'm using a bag of edges I'm using the bag class (which is where the add method comes from): http://algs4.cs.princeton.edu/code/edu/princeton/cs/algs4/Bag.java.html

The problem is that whenever I compile it, it says "error: variable V might not have been initialized" for line 32. Now because the MyEdgeWeightedGraph method calls the add method in the bag class, it doesn't need a return statement so how come I keep getting this error?

Upvotes: 1

Views: 85

Answers (1)

templatetypedef
templatetypedef

Reputation: 372982

In your constructor, when you write

    int E = in.readInt();
    int V = in.readInt();

you are creating local variables named E and V that shadow the fields E and V. As a result, after the constructor finishes running, the values of E and V, which you declared final, haven't been initialized, hence the error.

To fix this, remove the types and just write

    E = in.readInt();
    V = in.readInt();

This should fix your issue.

Upvotes: 0

Related Questions