CS 161 Lab #2

Thursday, September 10th

Do not submit anything as part of today's lab!

Goals:

In this week's lab you'll modify a project that draws the "face" from class. You'll get first hand experience with constructors that take parameters, and write code involving assignment and conditional statements. If you don't have time in lab to get through it all, I'd recommend that you try to finish it later for practice.

Directions:

  1. Download the Face project and extract its contents, then start BlueJ and open the project. (You can use the BlueJ copy you installed on Alexandria last week, or the version that's already installed on the lab machines. The local copy should run more quickly.)
  2. Create a new Face object by right-clicking on the Face class in the project window and selecting "new Face()". Right click on the resulting face object (the red rectangle on the workbench), invoke the draw method, and verify that it draws a colored face like the one below. Experiment with the setBlackAndWhite() and setColor() methods until you're sure you understand what they do to the picture.

  3. The face is pretty nice, but some may question the choice of green for the nose. A scientific poll of Tacoma residents shows massive disagreement regarding preferred nose colors. To keep them all happy, let's change the constructor so that it takes a parameter. We'll pass the desired color to the constructor when we create a Face, and use the parameter to determine the nose's color. It'll take a couple of steps to pull this off: We need a field to remember the nose's color, we need to modify the existing constructor so that it takes a parameter and stores it in the field for future reference. Finally, we need to modify the draw method so that it uses this new color information when drawing the nose.

  4. It seems a shame that our face doesn't have a mouth. Spend a few minutes extending the code to add a mouth. You'll need to add a new field at the top of the class in which to store the mouth object (you can choose what kind of object to use), and some new lines in the draw method that create the mouth and put it where it should be. (Don't worry about extending the setBlackAndWhite or setColor methods to deal with the mouth for now.) Make sure your mouth-drawing code works before going to the next step.
  5. Lots of people have gotten used to the mouthless face, and they may not appreciate the new addition. As a final act, let's make the mouth optional. We can do this by passing a second argument to the constructor — a boolean that specifies whether we want the mouth to be created or not.
If time permits, consider trying some of the following exercises:


Brad Richards, 2009