How to edit an array from another class in Java
arrays, java, static
Solution
You must change one of the two things:
declare `myGrid` as static
public static char[][] myGrid = new char[8][8];
access `myGrid` via an object instance:
PlayingBoard pb = new PlayingBoard();
int i, j;
for(i = 0; i < 12; i++) {
for(j = 0; j < 12; j++) {
pb.myGrid[i][j] = 'x';
}
}
Problem
I have created a 2d array (used as a playing board) and in another class I want to take my array and be able to perform operations on it. My array definition (in class `PlayingBoard`): ``` public char[][] myGrid = new char[12][12]; ``` Now I want to manipulate this array from other classes in my project. I tried to call this grid in the class it was not defined in ``` int i, j; for(i = 0; i < 12; i++) { for(j = 0; j < 12; j++) { PlayingBoard.myGrid[i][j] = 'x'; } } ``` I get the error: Non-static variable `myGrid` cannot be referenced from static context How can I reference, edit, and operate on `myGrid` from this second class?