-1

I am building an A* algorithm where i am suppose to add nodes to the grid[][] first ( in my case it is cells[i][j] ). So what i did is i run a loop in order to fill my 2D array with nodes with x and y coordinate filled inside it. But when ever i try to run my code it throws this exception java.lang.NullPointerException, i know this exception happens when object == null , but somehow i am not able to figure out the reason behind this problem, Here is my code :-

 private Node[][] cells;

 private void fill(){

    for(int i=0;i<rows;i++){
        for(int j=0 ; j<cols;j++){
            cells[i][j] = new Node(i,j,rows,cols); //throws exception this 
                                                     line
        }
    }
}

Please help me out to find the reason behind this.

Prags
  • 2,457
  • 2
  • 21
  • 38
Jas world
  • 33
  • 7

2 Answers2

1

it is because you are not initializaing cells array. Just inititalize it to proper size , then it should not be a problem. For example:

cells = new Node[5][5];
codeLover
  • 2,571
  • 1
  • 11
  • 27
0

Just try ArrayList<ArrayList<Node>> if you don't know the size of array.

private ArrayList<ArrayList<Node>> nodes = new ArrayList<>();

for(int i=0;i<rows;i++){
       ArrayList<Node> n  = new ArrayList<>();
        for(int j=0 ; j<cols;j++){
           Node node =  new Node(i,j,rows,cols); //throws exception this 
                                                               line
           n.add(node )

        }
      nodes.add(n);
    }

If you know the size then use Node[][] nodes = new Node[10][10].

sushildlh
  • 8,986
  • 4
  • 33
  • 77