How to edit an array from another class in Java

I created a 2d array (used as a playing field), and in another class I want to take my array and perform operations on it.

Defining my array (in the PlayingBoard class):

 public char[][] myGrid = new char[12][12]; 

Now I want to manipulate this array from other classes in my project. I tried calling this grid in a class that 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 an error message:

The non-static variable myGrid cannot refer to a static context

How can I reference, edit and work with myGrid from this second class?

+8
java arrays static
source share
2 answers

You must change one of two things:

  • declare myGrid as static

     public static char[][] myGrid = new char[8][8]; 
  • access myGrid through an instance of an object:

     PlayingBoard pb = new PlayingBoard(); int i, j; for(i = 0; i < 12; i++) { for(j = 0; j < 12; j++) { pb.myGrid[i][j] = 'x'; } } 
+6
source share

The answers point to the use of a static array, and that makes me feel sad in terms of OO.

How about getting your game pad to have a properly encapsulated structure with the 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 parts themselves are smart, you need to create an object that wraps them, and not just store the char.

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

Also, you use 12 in the loop, but 8 in the initialization, so expect IndexOutOfBounds exceptions.

+1
source share

All Articles