Reputation: 815
I'm creating a graph of flights where the user I want to be able to print my graph out like:
Edinburgh <-> Heathrow
Heathrow <-> Amsterdam
etc....
I have an idea to do this by getting the edge source and the edge target, the edge being the "<->" , the source being for example "Edinburgh" and the target being "Heathrow".
I've tried looping through the String array and printing, such as graph.getEdge(sourceVertext, targetVertex), but I can't seem to get it working.
I'll only use a couple of examples in the code.
Note: If I try printing the array after setting edge weights, I get an illegal argument exception. If anyone could please explain why this is happening that would also be great :) thanks.
public static void main(String[] args) {
SimpleDirectedWeightedGraph<String, DefaultWeightedEdge> airport = new SimpleDirectedWeightedGraph<String, DefaultWeightedEdge>(
DefaultWeightedEdge.class);
String[] array = { "Edinburgh", "Heathrow", "Amsterdam" };
System.out.println(" ");
System.out.println("The following destinations are used: " + "\n");
for (String s : array) {
System.out.println(s); // prints the array elements
}
System.out.print("");
for (String s : array) {
System.out.print(airport.getEdgeSource(s) + airport.getEdgeTarget(s));
// OR....
// System.out.print(airport.getEdge(sourceVertex, targetVertex));
}
DefaultWeightedEdge EH1 = airport.addEdge("Edinburgh", "Heathrow");
DefaultWeightedEdge HE1 = airport.addEdge("Heathrow", "Edinburgh");
airport.setEdgeWeight(EH1, 110);
airport.setEdgeWeight(HE1, 110);
DefaultWeightedEdge HA2 = airport.addEdge("Heathrow", "Amsterdam");
DefaultWeightedEdge AH2 = airport.addEdge("Amsterdam", "Heathrow");
airport.setEdgeWeight(HA2, 100);
airport.setEdgeWeight(AH2, 100);
System.out.println("");
}
Upvotes: 1
Views: 5019
Reputation: 815
I've since figured out how to display the edge source and target:
for(DefaultWeightedEdge e : airport.edgeSet()){
System.out.println(airport.getEdgeSource(e) + " --> " + airport.getEdgeTarget(e));
}
This displays it like:
Edinburgh --> Heathrow
Heathrow --> Edinburgh
Thanks.
Upvotes: 3