Hello Members,

I am trying to add weights to a Graph that is implemented using JGrapht. I keep getting a
NullPointerException, which I am unable to understand as all other edges seems to be added fine. I would be grateful for any help.

The code so far:

import org.jgrapht.*;
import org.jgrapht.alg.*;
import org.jgrapht.graph.*;
import java.util.List;

public class Graph {
    public static void main(String args[]) {
     
        SimpleWeightedGraph<String, DefaultWeightedEdge>  graph = new SimpleWeightedGraph<String, DefaultWeightedEdge>(DefaultWeightedEdge.class); 
        graph.addVertex("47");
        graph.addVertex("28");
        graph.addVertex("29");
        graph.addVertex("26");
        graph.addVertex("79");
        
        
        DefaultWeightedEdge e1 = graph.addEdge("47", "28"); 
        graph.setEdgeWeight(e1, 5); 
        
        DefaultWeightedEdge e2 = graph.addEdge("28", "29"); 
        graph.setEdgeWeight(e2, 3); 
        
        DefaultWeightedEdge e3 = graph.addEdge("26", "79"); 
        graph.setEdgeWeight(e3, 6); 
        
        DefaultWeightedEdge e4 = graph.addEdge("28", "26"); 
        graph.setEdgeWeight(e4, 2); 
        
        DefaultWeightedEdge e5 = graph.addEdge("79", "26"); 
        graph.setEdgeWeight(e5, 4); 
        
       
        DefaultWeightedEdge e6 = graph.addEdge("28", "79"); 
        graph.setEdgeWeight(e6, 9); 
        
        DefaultWeightedEdge e7 = graph.addEdge("26", "47"); 
        graph.setEdgeWeight(e7, 7); 
        
        DefaultWeightedEdge e8 = graph.addEdge("29", "28"); 
        graph.setEdgeWeight(e8, 2); 
        
        DefaultWeightedEdge e9 = graph.addEdge("47", "29"); 
        graph.setEdgeWeight(e9, 10); 
        
        DefaultWeightedEdge e10 = graph.addEdge("29", "79"); 
        graph.setEdgeWeight(e10, 1); 
        

       
        System.out.println("Shortest path from 47 to 79:");
        List shortest_path =   DijkstraShortestPath.findPathBetween(graph, "47", "79");
        System.out.println(shortest_path);
        
    }
}

The run-time exception:

java.lang.NullPointerException
	at org.jgrapht.graph.AbstractBaseGraph.setEdgeWeight(Unknown Source)
	at Graph.main(Graph.java:32)

Recommended Answers

All 3 Replies

Hello,

Thank you for the reply. What I am unable to understand is that I am getting a NullPointerException only when I add the fifth and the eight edge. If I comment those off, the program works accurately. Just wondering what is so error-prone about adding those two edges when all other edges are similarly added and work acucrately.

Thank you!

Hello,

It works now - I should have used SimpleDirectedWeightedGraph.

Thank you!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.