I am trying to create an indirect graph read from a text file. However I keep getting a NullPointerException. This is my graph class:
Graph.java:
package testalgo; Import java.io.file; Import java.util.ArrayList; Import java.util.HashMap; Import java.util.LinkedList; Import java.util.list; Import java.util.Scanner; Public Class Graph {ArrayList & lt; Integer & gt; Brackets = new arreelist & lt; Integer & gt; (); Hashmap & lt; Integer, linked list & lt; Integer & gt; & Gt; Adj Stable scanner scan; Public graph (arrelist & lt; integer> vertex) {adj = new hashmap & lt; Integer, linked list & lt; Integer & gt; & Gt; (); } Public static zero main (string [] args) {try {sc = new scanner (new file ("graph1.txt")); } Hold (exception e) {System.out.println (e); } While (sc.hasNext ()) {int a = integer ParseInt (sc.next ()); Int b = integer.centre (sc.next ()); Graph G = new graph (new altreist ()); G.addVertex (a); G.addeEgde (A, B); // this line is 46 g ADEgade (B, A) is; } Sc.close (); } Public Zero addVertex (int v) {for (int i = 1; i & lt; vertices.size (); ++ i) {adj.put (i, new linked list & lt; integer & gt; ()); }} Public void addeEgde (int v1, int v2) {adj.get (v1) .add (v2); // this line 68} public list & lt; Integer & gt; Millennibbers (int v) {return adj.get (v); }}
And this is an error message that I am getting:
Exception in the thread "main" on java.lang.NullPointerException testalgo.Graph. AddeEgde (Graph.java:68) on testego.Graph.main (graph.java:46)
Thank you for all your help!
I can not see anywhere where you adj
map to V
will return
adj.get (v1)
back to null
as a key. You have just declared adj
; You have to populate it too.
All I am looking for:
for (int i = 1; i & lt; vertices.size (); ++ i) {Adj.put ( I, new linked list & lt; integer & gt; ()); }
Since is open to start with siroshinu
, you will not include anything in your map.
Did you mean: / P>
adj.put (v, new linked list & lt; integer & gt; ());
Instead?
In response to your comment: You must add another entry to b
in your nearest list:
g.addVertex (a) ; G.addVertex (b); // & lt; --- You need g.addeEgde (a, b); G.addeEgde (B, A); // & lt; --- Otherwise you will find an NPE here
No comments:
Post a Comment