Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to edit an array from another class in Java [duplicate]

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?

like image 619
LeonH Avatar asked Dec 02 '13 17:12

LeonH


People also ask

Can you modify an array in Java?

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.

Can we clone an array in Java?

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.


1 Answers

You must change one of the two things:

  1. declare myGrid as static

    public static char[][] myGrid = new char[8][8];
    
  2. 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';
        }
    }
    
like image 66
twester Avatar answered Nov 10 '22 22:11

twester