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?
No, we cannot change array size in java after defining. Note: The only way to change the array size is to create a new array and then populate or copy the values of existing array into new array or we can use ArrayList instead of array.
Java allows you to copy arrays using either direct copy method provided by java. util or System class. It also provides a clone method that is used to clone an entire array.
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';
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With