Java compiler error

Cell[][] cells = new Cell[30][20];
for(int x = 0; x < cells.length; x++)
{
      for(int y = 0; y <  cells[x].length; y++)
      {
            cells[x][y] = new Cell(x, y);
      }
}

This code produces the following error:

error: non-static variable this cannot be referenced from a static context
                cells[x][y] = new Cell(x, y);
                              ^

That code is found in the main method. Cell is just created at the bottom like this:

class Cell
    {
        public int x, y;
        public boolean visited = false;
        public Cell(int x, int y)
        {
            this.x = x;
            this.y = y;
        }
    }

I can’t think of a reason why this would be giving me trouble aside from an error in the site’s compiler.

Put a static before your Cell class, because, otherwise, it’s an inner class (instead of just a nested class) that you can’t create from a static context (i.e. your main method).

(P.S. The probability of CG using a custom Java compiler developed inhouse instead of the Oracle or Open JDK is 0.00000001.)

2 Likes