Hi everyone,

I'm working on method to fill a 2D grid with objects. This is what I have at the moment:

public void fillGrid() {
    	for(int i = 0; i < ROWS; i++) {
    		for(int j = 0; j < COLUMNS; j++) {
    			String displayText = "#";
    			board[i][j] = new objPiece(displayText);
    		}
    	}
    }

board = new objPiece[8][8];

What does 'design for flexibility' mean for this method? It is expected that this method will fill in different objPiece in later updates (maybe an objPiece with a display string of "@" or "*" or "$" on different locations in the grid).

All ideas are welcome :)

You can pass the displayText as a parameter

public void fillGrid(String displayText) 
{
   for(int i = 0; i < ROWS; i++) 
   {
      for(int j = 0; j < COLUMNS; j++) 
      {
    	 board[i][j] = new objPiece(displayText);
      }
   }
}

Hi apines,

Thank you for the suggestion. I've thought about this initially but that would just fill the entire grid with the same displayString. On a 4 x 5 grid for example:

####
####
####
####
####

I'm stumped on how to make it flexible enough to fill the grid like:

#@@#
#oo#
####
#oo#
#@@#

I'm thinking this method will be like setting up a chess grid with pre-positioned objects in the next exercise.

Well, for maximum flexibility you can always pass the 2D array as a parameter. If you pass a displayText 2D array as the parameter, you will be able to initialize each objPiece with its own displayText.

I think we're on to something. Instead of passing the 2D array (board), the method could accept row/column parameters in addition to objPiece to update a specific point in the grid. The 2D array already has class scope and will be accessible even without having to pass it to the method. And I'm assuming that there will always be just one board in the program though.

Thank you for the ideas apines :icon_smile:

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.