简体   繁体   中英

Error in java: Exception in thread "main"

I am trying to apply Dijkstra algorithm in java. the input will be from text file that contains 3 columns the first one is the start node and the third is the end node and the second one is the relation name but I do not need it right now so I use the first and last column. The text file is:

 12 ECrel 15 15 ECrel 18 11 ECrel 12 12 ECrel 14 11 ECrel 14 11 ECrel 18 14 maplink 17 12 maplink 17 14 maplink 10 18 maplink 10 14 maplink 16 15 maplink 19 18 maplink 19 12 maplink 19

can any one please take a look to my code and help me to find what is the problem in the code that cause this error. the code is as bellow:

package shortestPath;
import java.util.Scanner;
import java.io.*;
import java.util.*;

public class Dijkstra {


    public static int count;
    //public static Graph.Edge[] GRAPH = new Graph.Edge[count] ;

    public static void countLines(String file) throws IOException
    {
    LineNumberReader  lnr = new LineNumberReader(new FileReader(new File(file)));
    lnr.skip(Long.MAX_VALUE);
    Dijkstra.count=lnr.getLineNumber() + 1; //Add 1 because line index starts at 0
    // Finally, the LineNumberReader object should be closed to prevent resource leak
    lnr.close();
    //return Dijkstra.count;
    }

    public static Graph.Edge[] readTextFile(String fileName) {

    String line = null;
    Graph.Edge[] Gr=new Graph.Edge[Dijkstra.count];
    try {
        FileReader fileReader = new FileReader("hsa00072.txt");
        // Always wrap FileReader in BufferedReader.
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        // BufferedReader br = new BufferedReader(new InputStreamReader(new
        // FileInputStream(file)));
        int i=0;
        while ((line = bufferedReader.readLine()) != null) {
            String[] tokens = line.split("\\t+");
            String s = tokens[0];
            String e = tokens[2];
            Gr[i] =new Graph.Edge(s, e, 1);
            i=i+1;
        }

        // Always close files.
        bufferedReader.close();
    } catch (FileNotFoundException ex) {
        System.out.println("Unable to open file '" + fileName + "'");
    } catch (IOException ex) {
        System.out.println("Error reading file '" + fileName + "'");
    }
    //return Dijkstra.GRAPH;
    return Gr;
    }


       private static final String START = "10";
       private static final String END = "12";

       public static void main(String[] args) throws IOException {
          countLines("hsa00072.txt"); 
          Graph.Edge[] GRAPH=readTextFile("hsa00072.txt");
          Graph g = new Graph(GRAPH);
          g.dijkstra(START);
          g.printPath(END);


          //g.printAllPaths();
       }
    }

    class Graph {
       private final Map<String, Vertex> graph; // mapping of vertex names to Vertex objects, built from a set of Edges

       /** One edge of the graph (only used by Graph constructor) */
       public static class Edge {
          public final String v1, v2;
          public final int dist;
          public Edge(String v1, String v2, int dist) {
             this.v1 = v1;
             this.v2 = v2;
             this.dist = dist;
          }
       }

       /** One vertex of the graph, complete with mappings to neighbouring vertices */
       public static class Vertex implements Comparable<Vertex> {
          public final String name;
          public int dist = Integer.MAX_VALUE; // MAX_VALUE assumed to be infinity
          public Vertex previous = null;
          public final Map<Vertex, Integer> neighbours = new HashMap<>();

          public Vertex(String name) {
             this.name = name;
          }

          private void printPath() {
             if (this == this.previous) {
                System.out.printf("%s", this.name);
             } else if (this.previous == null) {
                System.out.printf("%s(unreached)", this.name);
             } else {
                this.previous.printPath();
                System.out.printf(" -> %s(%d)", this.name, this.dist);
             }
          }

          public int compareTo(Vertex other) {
             return Integer.compare(dist, other.dist);
          }
       }

       /** Builds a graph from a set of edges */
       public Graph(Edge[] edges) {
          graph = new HashMap<>(edges.length);

          //one pass to find all vertices
          for (Edge e : edges) {
             if (!graph.containsKey(e.v1)) graph.put(e.v1, new Vertex(e.v1));
             if (!graph.containsKey(e.v2)) graph.put(e.v2, new Vertex(e.v2));
          }

          //another pass to set neighbouring vertices
          for (Edge e : edges) {
             graph.get(e.v1).neighbours.put(graph.get(e.v2), e.dist);
             //graph.get(e.v2).neighbours.put(graph.get(e.v1), e.dist); // also do this for an undirected graph
          }
       }

       /** Runs dijkstra using a specified source vertex */ 
       public void dijkstra(String startName) {
          if (!graph.containsKey(startName)) {
             System.err.printf("Graph doesn't contain start vertex \"%s\"\n", startName);
             return;
          }
          final Vertex source = graph.get(startName);
          NavigableSet<Vertex> q = new TreeSet<>();

          // set-up vertices
          for (Vertex v : graph.values()) {
             v.previous = v == source ? source : null;
             v.dist = v == source ? 0 : Integer.MAX_VALUE;
             q.add(v);
          }

          dijkstra(q);
       }

       /** Implementation of dijkstra's algorithm using a binary heap. */
       private void dijkstra(final NavigableSet<Vertex> q) {      
          Vertex u, v;
          while (!q.isEmpty()) {

             u = q.pollFirst(); // vertex with shortest distance (first iteration will return source)
             if (u.dist == Integer.MAX_VALUE) break; // we can ignore u (and any other remaining vertices) since they are unreachable

             //look at distances to each neighbour
             for (Map.Entry<Vertex, Integer> a : u.neighbours.entrySet()) {
                v = a.getKey(); //the neighbour in this iteration

                final int alternateDist = u.dist + a.getValue();
                if (alternateDist < v.dist) { // shorter path to neighbour found
                   q.remove(v);
                   v.dist = alternateDist;
                   v.previous = u;
                   q.add(v);
                } 
             }
          }
       }

       /** Prints a path from the source to the specified vertex */
       public void printPath(String endName) {
          if (!graph.containsKey(endName)) {
             System.err.printf("Graph doesn't contain end vertex \"%s\"\n", endName);
             return;
          }

          graph.get(endName).printPath();
          System.out.println();
       }
       /** Prints the path from the source to every vertex (output order is not guaranteed) */
       public void printAllPaths() {
          for (Vertex v : graph.values()) {
             v.printPath();
             System.out.println();
          }
       }

    }      

The error message is :

 Exception in thread "main" java.lang.NullPointerException at shortestPath.Graph.<init>(Dijkstra.java:125) at shortestPath.Dijkstra.main(Dijkstra.java:69)

line 69 is:

Graph g = new Graph(GRAPH);

line 125 is

if (!graph.containsKey(e.v1)) graph.put(e.v1, new Vertex(e.v1));

Thanks for all your comments but special thank to David Wallace whose comment helped me to know the problem that caused this error. The problem is in this line

Graph.Edge[] Gr=new Graph.Edge[Dijkstra.count];

I had to set the size to count-1 instead of count.

Thank you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM