引用另一个数组时,空指针异常 - java深度优先搜索

时间:2018-06-03 22:05:32

标签: java

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;
        }
    }

不确定为什么我在这里得到一个空指针?根据我的理解,空指针是指什么东西没有得到正确的初始化 - 任何指导?

我尝试做的是将顶点的邻居添加到输入中。一个可能的问题是在Vertex类中我将Vertex数组的大小初始化为大小,但我没有看到任何其他方法来准确地获得数组的大小。

我还没有看到像这样的任何其他在线问题,因此为什么我要问!

0 个答案:

没有答案