CSC 212: Programming with Data Structures

Homework 2: Viewing Maps

Due: Wednesday, Feb. 10, 11:59pm

Credit for this assignment: Nick Howe


Class Specifics: MapGrid

The only field needed for MapGrid is a 2D array of Color. (You do not need to store the dimensions of the map separately, because the dimensions of an array arr can be found using arr.length. If arr is a 2D rectangular array, then the second dimension is arr[0].length.) The constructor for MapGrid should take arguments specifying the height and width, allocate an array of that size, and perhaps fill it in with some default color.

Create accessor methods to return the map height, width, and the contents of any specified square. Finally, you will need at least one method that will allow you to alter the map. A simple option is to create a method that takes row and column indices plus a Color and replaces the value stored at that point in the array. This is good, but may be tedious to use. Instead, you can also try to devise a method that will fill a rectangular area of the MapGrid with a specified color. By repeatedly calling this with various arguments, you will be able to create simple scenes like the one shown on the main page. You could specify the area to fill using four int arguments, but a better way is to use the Java Rectangle class which is designed to describe rectangular areas. You may also define other methods to change the map in different ways if you wish.

Two-dimensional arrays are really just an array of arrays. If you want to process every member of a 2D array you will need a pair of nested loops, the outer one loops over the rows, and the inner one loops over each column in the current row. (It is valid for the outer loop to move over columns, and the inner loop to move over rows, but the first way is more common/conventional.)

Here's an example showing how to create a 3x4 array of integers, and fill the elements with consecutive integers. Below is a diagram of the memory structures that would be created as a result. You should be able to generalize from this to figure out how to create and use a 2D array of Color.


int[][] arr2d = new int[3][4];
int count = 0;
for (int i = 0; i < arr2d.length; i++) {
    for (int j = 0; j < arr2d[i].length; j++) {
        arr2d[i][j] = count;
        count += 1;
    }
}

demo