0

I'm relatively new to programming and here I'm basically making an adjacency list (adjacency graph concept), using and array of linked list.

Scanner newSC = new Scanner(is_not_a_file);
        int noOfNodes = newSC.nextInt();
        LinkedList<Integer>[] adjlist = new LinkedList[noOfNodes];
        int i = 0, m = noOfNodes;
        while(i<=8){ //0 to 8. There are 9 lines of data in the text file 
            //(SmolFile.txt) after the first line (nOfNodes, which is 6).
            int temp = newSC.nextInt();
            int temp2 = newSC.nextInt();
            if (adjlist[temp] == null) {
                adjlist[temp] = new LinkedList<Integer>();
            }
            adjlist[temp].add(temp2);
            i++;
        }
        System.out.println("Adjency list with length of "+adjlist.length+": ");
        for(int x = 0;x<adjlist.length;x++){
            System.out.print(x+"-->");
            System.out.print(adjlist[x].toString());
            System.out.println();

        }

I get the error on the "System.out.println(adjlist[x].toString());", which is a NullPointerException. But I have no idea why it should have such an error given the array has a length of 6 elements and the "x" is stopping at x=5

The error output:

0-->[3, 1, 5]

1-->[4, 5]

2-->[4]

3-->[4, 5]

4-->[5]

Exception in thread "main" java.lang.NullPointerException at cselab1.CSELab1.main(Work42.java:80) 5-->C:\Users\Lenovo\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1 BUILD FAILED (total time: 0 seconds)

the "5-->" coming in the line of "C:\Users\Lenovo..." is a visual glitch, and not the problem. Its just that when x = 5, I have a null pointer exception.

For reference, the adjacency graph is "Directed" and the textfile contents than I'm reading from is:

6

0 3

0 1

0 5

1 4

1 5

2 4

3 4

3 5

4 5

Here is the adjacency matrix that runs from the same text file, for a visual representation:

0 1 2 3 4 5

0| 0 1 0 1 0 1

1| 0 0 0 0 1 1

2| 0 0 0 0 1 0

3| 0 0 0 0 1 1

4| 0 0 0 0 0 1

5| 0 0 0 0 0 0

I don't know where I'm doing wrong on printing it. Any advice will be heavily appreciated. Thank you.

  • Well, you array has 6 elements, but all your data lines in the file start with values from 0 to 4. So you never initialize the element at index 5 of your array. So it's null. Make it simpler: initialize all the elements to empty lists first. – JB Nizet Jan 24 '20 at 15:15
  • I see now, and yep, initializing it did solve the problem. Thanks! – Aadi880 Jan 25 '20 at 16:06

0 Answers0