9

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?

BartoszKP
  • 34,786
  • 15
  • 102
  • 130
LeonH
  • 1,039
  • 2
  • 22
  • 45

2 Answers2

7

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';
        }
    }
    
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
twester
  • 314
  • 4
  • 12
2

The answers point to the use of a static array and this makes me feel sad from an OO point of view.

How about ensuring your playing board has a properly encapsulated structure, with an "addPiece" method?

PlayingBoard myBoard = new PlayingBoard();

int i, j;
for(i = 0; i < 12; i++) {
    for(j = 0; j < 12; j++) {
        myBoard.addPiece(i,j, 'x');
    }
}

Even then, if your pieces themselves are "smart", you'll want to create an object that wraps them rather than just storing a char.

public PlayingPiece[][] _board = new PlayingPiece[8][8];

Also, you're using 12 in the loop but 8 in the initialisation, so expect an IndexOutOfBounds exception.

Jeff Watkins
  • 6,343
  • 16
  • 19
  • Thanks for pointing out my mistake, I was only updating the question though.. I wanted it to be useful for whoever else got this problem rather than the mess it was! – LeonH Aug 20 '14 at 12:52