Pregunta

I'm trying to make a Grid Class to use in a Sketch I want to make (I'm using Processing) but I get a NullPointerException when trying to access the grid variable from a method printGrid() of the Grid Class.

Code:

Grid_Proj:

Grid gridObj;

void setup() {
  size(480, 360);
  background(0);

  gridObj = new Grid(10, 10);

  gridObj.printGrid();
}

Grid:

class Grid {

  int[][] grid;                               // Declare the Grid

  Grid(int size_x, int size_y) {

    int grid[][] = new int[size_x][size_y];   // Initialize the Grid

    for (int x=0;x<size_x;x++) {
      for (int y=0;y<size_y;y++) {
        grid[x][y] = 0;
      }
    }

    println("Created Grid Object with: ", size_x, size_y);
  }

  void printGrid() {

    for (int x=0;x<10;x++) {
      for (int y=0;y<10;y++) {
        print(grid[x][y]);     // NPE Error here
      }
      print('\n');
    }
  }
}

I'm obviously doing something wrong here, but I can't figure out what. I also tried using

this.grid[x][y]

to no avail.

¿Fue útil?

Solución

int grid[][] = new int[size_x][size_y]; 

You are declaring a new local grid variable here, not initializing the field. Therefore, the grid field remains null and you receive an NPE when you try to index it. Try this instead:

grid = new int[size_x][size_y];  // use the field `grid`

As an aside, it's recommended in Java to put the [] of array declarations directly after the array type:

int[][] grid  // good
int grid[][]  // bad

You do this correctly when declaring the field, but not in the local variable declaration.

Otros consejos

In your constructor, you're initializing grid as a method-scoped variable, so you're never assigning any value to your instance field.

That's why you're instance method printGrid, which does reference the instance field, throws a NullPointerException.

Just remove int from the assignment in the constructor.

It's because in your constructor, you create a local grid array. Just don't create the local variable and you should be fine:

public Grid(int size_x, int size_y) {
    this.grid = new int[size_x][size_y];

    for (int x=0;x<size_x;x++) {
        for (int y=0;y<size_y;y++) {
            this.grid[x][y] = 0;
        }
    }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top