Computer Science 120
Introduction to Programming

Fall 2011, Siena College

2D Arrays - Birthday Grid

Overview

Implementation

Basic Setup

1. Create a new folder called lab8

2. Create a new BlueJ project called Arrays and save it your lab8 folder.

3. Create a new class called BirthdayGrid

Getting Started

Add the following to create BirthdayGrid:

import objectdraw.*;
 
public class BirthdayGrid extends WindowController {
   private static final int WIDTH = 50;
   private static final int HEIGHT = 30;
 
   private int months;
   private int years;
   
   private Text monthSum;
   private Text yearSum;
   
   private Text[] monthArray;
   private Text[] yearArray;
   
   private FramedRect[][] grid;
   private Text [][] text;
   private int [][] birthdayCount;

Creating the Grid

Add the following code to your begin method to create your headers

public void begin() {

months = 12; years = 7; monthArray = new Text[months]; yearArray = new Text[years];
String[] monthNames = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
 for (int m = 0; m < months; m++) {
   monthArray[m] = new Text(monthNames[m], 20, HEIGHT*m+HEIGHT, canvas);
 }
 for (int y = 0; y < years; y++) {
   yearArray[y] = new Text(1988 + y,WIDTH*y+50, 10, canvas);
 }

Task 1: Use the code above as a model and create the nested loop to generate the grid of FramedRectangles.

Here is some starter code:

for (int m = 0....) {
for (int y = 0...) {
grid[m][y] = ?
}
}

Task 2: Create the nested loop to generate the Text objects (2D text array) inside each Rectangle

Here is some starter code:

for (int m = 0....) {
for (int y = 0...) {
?
}
}

Task 3: Create the nest loop to set all the birthdayCounts to zero

Implementing onMouseClick

Remember that p is the location of your mouse click

public void onMouseClick(Location p) {

}

Task 1 - Incrementing Birthday Count: Test to see if each FramedRectangle (grid[m][y]) contains p (i.e., the clicked Location)

Here is some starter code:

for (int m = 0....) {
for (int y = 0...) {
if (?) {
// increment birthdayCount
// set the text of text[m][y] to the new value for birthdayCount
}
}

Task 2 - Add up the counts for a month: Test to see if a month label (monthArray) was clicked. If yes, iterate over all the years for that month (birthdayCount[m][?]) and sum all the values. Then, output the sum by setting the text of monthSum and placing it on the canvas.

Here is some starter code:

for ("each month") {
if (monthArray contains p) {

// set sum to zero
for ("each year") {
// increment sum by the birthdayCount
}
// Output the sum by creating a new Text object (monthSum) and placing it on the canvas
}
}

Task 3 - Add up the counts for the year: Test to see if a year label (yearArray) was clicked. If yes, iterate over all the months for that year (birthdayCount[?][y]) and sum all the values. Then, output the sum by setting the text of yearSum and placing it on the canvas.