0
public class Solution {

    public static void main(String[] args) throws Exception { //have this return the result of DFS

        Scanner input = new Scanner(System.in);
        int vertices = input.nextInt();
        Graph mygraph = new Graph (vertices);
        int edges = input.nextInt();

        //set up input as edges
        while (input.hasNextInt()) {
            int from = input.nextInt() - 1;
            int to = input.nextInt() - 1;
            //add the reciprocating vertex neighbors
            mygraph.nodes[from].addNeighbor(mygraph.nodes[to]);//null pointer here
            mygraph.nodes[to].addNeighbor(mygraph.nodes[from]);
        }

    }
}

class Graph {
    int size;
    Vertex[] nodes;

    Graph(int size) {
        this.size = size;
        this.nodes = new Vertex[size];
    }  

}

class Vertex {
    int value;
    Vertex[] neighbors;
    int available;


    Vertex(int value) {
        this.value = value;
        this.neighbors = new Vertex[50];
        this.available = 0;
    }

    //add to the neighbors list of this array
    void addNeighbor(Vertex v) {
        this.neighbors[this.available] = v;
        this.available = this.available + 1;
    }
}

not sure as to why I'm getting a null pointer here? To my understanding, null pointers are when something is not getting initialized properly--any guidance?

What I'm trying to do is add the neighbors of vertices to one another as they come up in the input. One possible issue is that in the Vertex class I'm initializing the size of the Vertex array as size, but I don't see any other way to accurately get the size of the array.

I haven't seen any other problem online like this one, hence why Im asking!

alexrnov
  • 2,346
  • 3
  • 18
  • 34
MScoder5
  • 3
  • 4
  • Possible duplicate of [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Turing85 Jun 03 '18 at 22:12
  • i looked at this one and still wasn't able to find the problem... – MScoder5 Jun 03 '18 at 22:14
  • 1
    Your code `nodes = new Vertex[size];` creates a vector of `size` elements, each of which is a null reference. You need to initialize each element with `nodes[i] = new Vertex(whatever);`. See https://stackoverflow.com/questions/5889034/how-to-initialize-an-array-of-objects-in-java – FBergo Jun 03 '18 at 22:15
  • You never initialze the entries in your `nodes`-array. – Turing85 Jun 03 '18 at 22:16
  • @FBergo `new Vertex[size]` creates an array. A [`Vector`](https://docs.oracle.com/javase/10/docs/api/java/util/Vector.html) is something else. – Turing85 Jun 03 '18 at 22:17

0 Answers0