-1

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;
  • Show the initialization of worldArray. Are you certain it was initialized properly? Also, to be safe, in your for loop you should go until `j < cells.length` instead. – Simeon G Dec 30 '20 at 22:30
  • This is my initialization Cell[][] worldArray = new Cell[40][40]; – HAKAN UTUŞ Dec 30 '20 at 22:32
  • The second "for" have the problem "for (int j = 0; j < worldArray[0].length; j++) ". Try to replace "0" with "i". – Andres Sacco Dec 30 '20 at 22:34
  • @AndresSacco he's using correct syntax there and that wouldn't cause an NPE anyway. – Simeon G Dec 30 '20 at 22:35
  • @SimeonG is right but i don't know what is the problem i think my array is initialized properly and loops are giving me what i want – HAKAN UTUŞ Dec 30 '20 at 22:38
  • 2
    You need to create each `Cell` object before you set a field in one of them. You could do that in your inner loop with `worldArray[i][j] = new Cell();` assuming the `Cell` class has a suitable constructor. – Dawood ibn Kareem Dec 30 '20 at 22:38
  • @DawoodibnKareem's answer worked for me, thank you all – HAKAN UTUŞ Dec 30 '20 at 22:41

1 Answers1

2

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/

Azizi
  • 268
  • 1
  • 7
Simeon G
  • 1,188
  • 8
  • 20