Reputation: 5
import java.util.*;
class Graph{
class Edge{
int v,w;
public Edge(int v,int w){
this.v=v; this.w=w;
}
@Override
public String toString(){
return "("+v+","+w+")";
}
}
List<Edge> G[];
public Graph(int n){
G=new LinkedList[n];
for(int i=0;i<G.length;i++)
G[i]=new LinkedList<Edge>();
}
boolean isConnected(int u,int v){
for(Edge i: G[u])
if(i.v==v) return true;
return false;
}
void addEdge(int u,int v,int w)
{
G[u].add(0,new Edge(v,w));
G[v].add(0,new Edge(u,w));
}
public int getWeight(int u, int v)
{
int w;
return w;
}
This part right above ^^^^. I'm trying to make it so that the code returns the correct number associated with the two numbers already input. For example g.getWeight(6,3) should return 13 since that is the weight in the graph for those two numbers.
@Override
public String toString(){
String result="";
for(int i=0;i<G.length;i++)
result+=i+"=>"+G[i]+"\n";
return result;
}
}
public class GraphEx
{
public static void main(String[] args)
{
Graph g=new Graph(10);
g.addEdge(1,2,38);
g.addEdge(1,5 ,19);
g.addEdge(1,3 ,35);
g.addEdge(1,4 ,11);
g.addEdge(4,3,27);
g.addEdge(3,6,13);
g.addEdge(3,5,28);
g.addEdge(5,6,26);
System.out.println(g);
g.getWeight(6,3);
}
}
The error the code as it currently stands gives is "variable w might not have been initialized"
Upvotes: 0
Views: 1555
Reputation: 11
in your code
public int getWeight(int u, int v)
{
int w; // There's no need, delete this
return w;
}
You were creating a new variable and didn't initialize it. And you have to search in G[], the right edge.
Upvotes: 1
Reputation: 140524
variable w might not have been initialized
This is because of Definite assignment.
Each local variable (§14.4) and every blank final field (§4.12.4, §8.3.1.2) must have a definitely assigned value when any access of its value occurs.
Unlike member variables, you have to assign local variables before you use their value. You can simply assign a value; but this won't do what you need yet:
int w = 0; // Or -1, or Integer.MAX_VALUE, or something.
To implement this method, you have to search through the edges of G[u]
, looking for an edge whose target is v
, and return its weight.
For example:
for (Edge e : G[u]) {
if (e.v == v) { return e.w }
}
throw new NoSuchElementException(); // Or return a default value.
Note that mixing arrays and generics is not a good idea:
List<Edge> G[];
Better to use a full-generics solution:
Map<Integer, List<Edge>> G = new HashMap<>();
Upvotes: 1