Search code examples
javaoopnullpointerexceptionarr

I get a null pointer error with the object array


I have a 2D object array i'm trying to store the data field "type" from a text file but i get a null pointer error.

 Cell[][] worldArray = new Cell[40][40];
 for (int i = 0; i < worldArray.length; i++) {
        String line = lines.get(i);
        String[] cells = new String[40];
        cells = line.split(";");
        if (cells.length != 40) {
            throw new IllegalArgumentException("There are " + i
                    + " cells instead of the 40 needed.");
        }
        for (int j = 0; j < worldArray[0].length; j++) {
            worldArray[i][j].type = Integer.parseInt(cells[j]);
        }

and this is my Cell class

 import java.awt.*;
 public class Cell {
 public static int cellSize;
 public int x;
 public int y;
 public int type;

Cell(int x, int y, int type) {
this.x = x;
this.y = y;
this.type = type;

Solution

  • You've initialized the object array properly:

    Cell[][] worldArray = new Cell[40][40];
    

    But at this point the array is empty with no values. In other words at a given point index like i,j, there is no Cell object there. You need to enter a new Cell object into these positions. So in your code here:

    for (int j = 0; j < worldArray[0].length; j++) {
            worldArray[i][j].type = Integer.parseInt(cells[j]);
    }
    

    You'll get an NPE when you do worldArray[i][j].type because worldArray[i][j] is null until you set a value to it. See here for an example of dealing with object arrays: https://www.geeksforgeeks.org/how-to-create-array-of-objects-in-java/