How to reference a 2D array from a static context?

arrays, definition, java, static

Solution

`myGrid` variable is an instance variable rather than a class variable. That is, it can only be accessed by an instance of `Zombies`. On the other hand, the static methods (and class, a.k.a. static, variables) belong to a class, which are shared, in this case, among all `Zombies` instances.

Either pass `myGrid` (`int[][]`) as parameter to each of these static methods, or declare it as `static`.

Problem

Every time I call `myGrid` in the `generateBoard` method, I get the error: non-static variable `myGrid` cannot be referenced from static context To my understanding, this shouldn't happen, because I've set the array to be public and should be able to be accessed from any other class. So have I set up the array incorrectly? ``` import java.util.Random; public class Zombies { private int Level = 1; private int MoveNo = 0; public int[][] myGrid = new int[12][12]; public static void generateBoard() { Random rand = new Random(); int i, j; for (i = 0; i < 12; i++) { for (j = 0; j < 12; j++) { if ( i == 6 && j == 6) { myGrid[i][j] = 'P'; } if (rand.nextInt(4) == 0) { myGrid[i][j] = 'I'; } myGrid[i][j] = 'x'; } } } public static String printBoard() { int i, j; for (i = 0; i < 12; i++) { for (j = 0; j < 12; j++) { if (j == 0) { System.out.print( "| " ); } System.out.print( myGrid[i][j] + " " ); if (j == 12) { System.out.print( "|" ); } } } } } ```

Original source