Wellesley College, Summer 2003

Problem Set 2

Due: Friday, June 20 by 10 am


About this Problem Set

This problem set is intended to help you understand how Java works and to give you practice using, designing, and writing methods. This problem set consists of a paper-and-pencil problem, two programming problem, and an optional extra credit programming problem.

To get the code for this assignment, connect to cs111 download directory via Fetch and download the folder ps2_programs from the directory /cs111d.

Reading

How to turn in this Problem Set

You are required to turn in both a hardcopy and a softcopy. For general guidelines on problem set submission, including how to submit a softcopy and how to check if you softcopy submission was successful, click here. Please make sure to keep a copy of your work, either on a zip disk, or in your private directory (or, to play it safe, both).

Hardcopy Submission of Required Problems

Your hardcopy packet for the required problems should consist of:
  1. The cover page;
  2. Your Execution Diagram from Task 1;
  3. Your modified Writing2.java file from Task 2;
  4. Your modified FlowerMaker.java file from Task 3.
Staple these together, and put your packet into the problem set box in room 257 by 10am on Fri. Jun 20.

Softcopy Submission of Required Problems

Save the modified Writing2.java file in your local version of the Writing2 folder and the the modified FlowerMaker.java file in your local version of the Flowers folder. Submit the entire copy of your ps2_programs folder to your drop folder on the cs111 server.

Hardcopy Submission of Optional Extra Credit Problems

If you work on any the optional extra credit problem, you should submit this in a separate packet. Your hardcopy packet for the extra credit problem should consist of your modified FontBuggle.java file. Slide the packet under the door of Elenas's office (E127).

Softcopy Submission of Optional Extra Credit Problems

If you work on the extra credit problem, submit your HuggleWorld folder to your ps2 drop folder on the cs111 server.


Task 1: Java Execution Model

In this part of the homework, you will use the Java Execution Model to draw an Execution Diagram that summarizes the execution of a simple Buggle program. It is important to become familiar with the conventions for drawing Execution Diagrams, since they are an important tool for explaining the behavior of Java programs. In particular, Execution Diagrams explain the meaning of method invocation, parameter passing, local variable declarations, and the this variable. You will be expected to draw an Execution Diagram on your midterm exam.

Before continuing with this problem, please study the conventions for drawing execution diagrams (i.e. your notes from lecture and the reading for this problem set).

Your JEM Assignment

Below are the declarations for two classes: a SwapWorld class that is a subclass of BuggleWorld and a SwapBuggle class that is a subclass of Buggle.


public class SwapWorld extends BuggleWorld { public void run () { SwapBuggle bg1 = new SwapBuggle(); SwapBuggle bg2 = new SwapBuggle(); SwapBuggle bg3 = new SwapBuggle(); Point pt1 = new Point(6,3); Point pt2 = new Point(4,5); bg1.setPosition(pt1); bg2.setPosition(pt2); bg3.setPosition(new Point(pt1.x-pt2.x, pt1.y+pt2.y)); bg2.setColor(Color.blue); bg1.setColor(Color.green); bg2.left(); bg3.right(); bg2.swap(bg3); bg3.swap(bg1); } }   class SwapBuggle extends Buggle { public void swap (Buggle bg1) { Point pt1 = this.getPosition(); Point pt2 = bg1.getPosition(); Color c1 = this.getColor(); Color c2 = bg1.getColor(); this.setPosition(pt2); bg1.setPosition(pt1); this.setColor(c2); bg1.setColor(c1); } }

Suppose that Object Land contains an instance of the SwapWorld class that has the reference label SW1. Your assignment is to draw an Execution Diagram for the execution of the statement

SW1.run()

Please be careful. This code is specifically designed to be tricky in a number of places. Be sure to pay attention to the following:


Task 2: Buggle Word Writing using Methods

It is possible to use methods to expand the capabilities of the buggle word writing program from Problem Set 1. For example, using a larger grid, but fewer actual lines of code, a buggle can write the word "JAVA" multiple times, around the perimeter of the grid, as shown below:

Your assignment:

In the folder Writing2 is a file Writing2.java that contains Java code that creates a 25x25 grid and defines LetterBuggle, a new class of objects that extends the Buggle class. A new LetterBuggle named ellie has also been created for you, along with the skeleton of two LetterBuggle methods: writeJava, and writeJ, as shown below:

public class Writing2 extends BuggleWorld {

    public void setup () {
        setDimensions(25,25); // magic for making 25x25 grid
    }

    //write the word "JAVA" around the perimeter of the grid
    public void run () {
        LetterBuggle ellie = new LetterBuggle();
        ellie.writeJava(Color.red, Color.blue, Color.yellow);

       // Add statements here that will write the word in various colors 
       // around the perimeter of the grid

     }
}

class LetterBuggle extends Buggle {

    // Write the word "JAVA", in the appropriately colored letters, by 
    // invoking methods with appropriate color parameters for writing the 
    // individual letters. Note that the J and the V are always the same color, 
    // but each A can be a different color from the color of the J and V.
    public void writeJava (Color c1, Color c2, Color c3) {

        this.writeJ(c1);//write the "J" in color c1
        // Add statements to write the "A V A" in the correct colors.

    }

    // write the letter "J" in color c
    public void writeJ (Color c) {

       // Flesh out the body of this method.

    }
		     
    // Define methods for writing "A" and "V" here. 
}
Perform the following steps to solve the problem: You must conform to the following rules:
  1. You may not invoke the setPosition or setHeading methods.
  2. You should use the methods brushUp and brushDown where appropriate.
  3. Each letter except "V" should fit in a 4x5 grid, and should be separated from the next letter by one blank space.
  4. The letter "V should occupy a 3x5 grid as shown.
  5. Ellie must draw the letters in the appropriate colors. All the colors used in the picture above are Color constants from the Color class. These constants are only used in the run method. They may not be used anywhere else in your code.
  6. Ellie must end up in the position shown above, facing the correct direction (EAST).
  7. Use methods to solve the problem.

Task 3: Flowers


Important note: Before you begin working the second task, make sure to close the project that you were using for the first task by choosing Close from the File menu to close . Then double-click on the FlowerWorld.mcp icon in the Flowers folder to open the second project.

Alternatively, to be on the safe side (i.e. to make sure that you are not running the code from the previous task instead of the new one), you might want to quit CodeWarrior entirely and reopen it for the new project. To do this

  1. quit CodeWarrior (File -> Quit),
  2. quit the Applet Runner by selecting Apple Applet Runner from the menu of active applications in the upper right corner of the screen, then choosing Quit from the File menu,
  3. double-click on the FlowerWorld.mcp icon to open the second project

Flora is a turtle who loves flowers. Here is a garden with three flowers that Flora would like to draw:

Flora is an instance of the FlowerMaker class, which extends the Turtle class. In this problem, you will flesh out the following methods in the FlowerMaker class to enable Flora to draw her garden. All code can be found in the file FlowerMaker.java within the Flowers folder.

public void diamond (double side)
Draws a diamond with internal angles of 60 and 120 degrees whose sides have length side. The state of the turtle is left unchanged after drawing the diamond. For instance, if flora is a red turtle facing up, here is the picture drawn by the invocation flora.diamond(100):

public void diamond4 (double side)
Draws four diamonds that fill an outer diamond of side length side. The state of the turtle is left unchanged after drawing the diamonds. For instance, if flora is a red turtle facing up, here is the picture drawn by the invocation flora.diamond4(100):

public void diamond16 (double side)
Draws sixteen diamonds that fill an outer diamond of side length side. The state of the turtle is left unchanged after drawing the diamonds. For instance, if flora is a red turtle facing up, here is the picture drawn by the invocation flora.diamond16(100):

public void flower (double side, Color inner, Color outer)
Draws a flower from the stem up in the direction the turtle is facing. The stem is green and is twice the length of side with two green leaves at its midpoint. The two outer petals consist of four diamonds of color outer fitting into a diamond with side length side. The inner (middle) petal consists of sixteen diamonds f color inner fitting into a diamond with side length side. The state of the turtle is left unchanged after drawing the flower, except for the color, which may be different from the initial color. For instance, if flora is a red turtle facing up, here is the picture drawn by the invocation flora.flower(100, Color.red, Color.blue):

public void garden ()
Assume the turtle is positioned at the middle bottom of the screen facing up. Draws the garden with three flowers pictured at the beginning of this problem description. Here are the details of the three flowers:

  1. Directly above the turtle is a flower with a yellow inner petal and red outer petals of side length 100.
  2. 250 units to the right of the initial turtle position is a flower with a pink inner petal and blue outer petals of side length 75.
  3. 200 units to the left of the initial turtle position is a flower with a magenta inner petal and cyan outer petals of side length 50.
The state of the turtle is left unchanged after drawing the flower, except for the color, which may be different from the initial color.

Your task is to flesh out the skeletons of the five methods in FlowerMaker.java so that they satisfy the method contracts given above.

Notes:


Extra Credit Task 4: HuggleWorld

This is a completely optional extra credit problem. You should only attempt it after finishing the rest of the assignment. Unlike the required tasks, you have until 10am Monday, June 23 to complete this extra credit task.

Background

The Story

Fontaine Buggle is very impressed by the creative work of her cousins at the Buggle Bagel Ruggle Company. But she thinks that buggles can use their considerable talents to do more than just drop bagels in interesting patterns.

Inspired by the buggle writing problem of Problem Set 1 (remember "Java"?), Fontaine wants buggles to be able to write words using letters of any color drawn in rectangles of arbitrary size and orientation. As a simple example of what can be done with this capability, Fontaine designs the following Valentine card:

Valentine Figure

The card uses the seven letters 'C', 'd', 'G', 'H', 'I', 'P', and 'U'. Note that the 'U' appearing in "CUPId" and "HUG" has the same basic shape even though it is written in rectangles of different sizes (a 5x5 rectangle in the case of the 'U' in "CUPId" and a 7x17 rectangle int the case of the 'U' in "HUG").

Letter Methods and their Contracts

Fontaine recognizes that methods can be used to capture the similarity in shape while abstracting over the color and rectangle size. She defines a new FontBuggle class that is a subclass of Buggle extended with methods that draw the seven letters of the Valentine card. For example, the FontBuggle class has a method for drawing the letter 'U' according to the following contract:

public void U (Color col, int width, int height);

Assume the initial brush state of this buggle is down. Consider the width by height rectangle such that this buggle is in the lower left hand corner facing along the width edge. Executing this method causes this buggle to draw the letter 'U' inscribed in the rectangle, as shown below. The heading of the buggle should not change, but its final position should be width + 1 cells in front of its original position, its final color should be col, and its final brush state should be down.

Fontaine defines similar methods for the other six letters, whose contracts are the same as that for U() except for the shape inscribed in the rectangle. The shapes drawn by the C(), d(), G(), H(), I(), and P() methods are depicted below:

Java Arithmetic

The dimensions in the above pictures are given in terms of Java integer arithmetic. Java integer arithmetic is pretty much what you would expect except that division of two integers always yields the integer that results by truncating (not rounding) the decimal portion of the exact result. For example:

n

n/2

n/3

n/4

5

2

1

1

6

3

2

1

7

3

2

1

8

4

2

2

9

4

3

2

The following equations are also always true (both in Java arithmetic and traditional arithmetic):

1 + (n/2) = (n + 2)/2

1 + ((n - 1)/2) = (n + 1)/2

The reason that we prefer the left-hand side versions to the right-hand side versions in the above diagram is that the left-hand side versions turn out to be more useful when drawing the letters with buggles. (See the note on fencepost errors in the tasks section, below.)

You should also convince yourself that in Java integer arithmetic, the following equation is always true (this equation is not true for traditional arithmetic!):

n = 1 + ((n - 1)/2) + (n/2)

Stringing Letters Together

The final position and heading of a FontBuggle after drawing a letter is designed to facilitate stringing letters together to form words. If the FontBuggle is asked to draw a new letter, both letters will be on the same "baseline", and there will be one cell of space between the previous letter and the new one. For example, consider the following method for drawing the word "CUP":

public void CUP () {
  C(Color.blue, 3, 5);
  U(Color.green, 8, 3);
  P(Color.red, 4, 12);
}

Invoking the CUP() method on a FontBuggle causes it to draw the following letters:

Buggle Jumping

Since letters do not always directly follow one another, it is useful to have the following jump() method, which changes the relative position of a FontBuggle by fwd units in the forward direction and lft units to its left. (Either number may be 0 or negative.)

	public void jump (int fwd, int lft) {
	  brushUp();
	  forward(fwd);
	  left();
	  forward(lft);
	  right();
	  brushDown();
	 }

Because the parameters to jump() are relative to the buggle's current position and heading, the method works regardless of the buggle's initial state. After jumping, it is often desirable to turn the buggle; the following three methods abstract over the three possible ways of turning:

	 public void jumpAndTurnLeft (int fwd, int lft) {
	   jump(fwd,lft);
	   left();
	 }
	 
	 public void jumpAndTurnRight (int fwd, int lft) {
	   jump(fwd,lft);
	   right();
	 }
	 
	 public void jumpAndTurn180 (int fwd, int lft) {
	   jumpAndTurnLeft(fwd,lft);
	   left();
	 }

As an example of buggle jumping, consider the following method:

	public void fourCUPs () {
	  CUP();
	  jumpAndTurnLeft(4, 0);
	  CUP();
	  jumpAndTurnLeft(4, 0);
	  CUP();
	  jumpAndTurnLeft(4, 0);
	  CUP();
	  jumpAndTurnLeft(4, 0);
	}

Invoking fourCups() on a FontBuggle at position (3,3) facing eastward yields the following picture:

fourCUPs Figure

As another example of buggle jumping, consider the following testFont() method that draws the C(), d(), G(), H(), I(), P(), and U() shapes for 5x5, 4x4, 3x5, 4x4, and 4x3 rectangles for both the east and north buggle orientations:

	public void testFont() {
	  testSizes();
	  jumpAndTurnLeft(27,0);
	  testSizes();
	}
	
	public void testSizes() {
	  testLetters(5,5);
	  jump(-42,6);
	  testLetters(4,5);
	  jump(-35,6);
	  testLetters(3,5);
	  jump(-28,6);
	  testLetters(5,4);
	  jump(-42,5);
	  testLetters(5,3);
	  jump(-42,4);
	}
	
	public void testLetters(int w, int h) {
	  C(Color.red, w, h);
	  d(Color.green, w, h);
	  G(Color.black, w, h);
	  H(Color.blue, w, h);
	  I(Color.yellow, w, h);
	  P(Color.magenta, w, h);
	  U(Color.cyan, w, h);
	}

Executing testFont() should yield the following result:

FontTest Figure


Your Tasks

Your tasks in the problem are to define the following eight FontBuggle methods:

You should begin the problem by downloading the HuggleWorld folder from the CS111 download folder. This folder has a file FontBuggle.java that contains skeletons of the eight methods you should define, as well as the jump(), jumpAndTurnLeft(), jumpAndTurnRight(), and jumpAndTurn180() methods described above.

The HuggleWorld folder also contains three .html for testing your methods:

Note that the applets depend on the letter methods and do not work correctly until all the letter methods are written.

Hints/Notes:


One advantage of methods is that they can be used to significantly shrink the size of a program, as measured by the number of lines of Java code. For the HuggleWorld program, we challenge you to see how small you can make your FontBuggle class and still have it work correctly.

Traditionally, program size is measured by the number of lines in the program. Because this metric is very sensitive to the way you format your program (commenting, use of whitespace, placement of squiggly brackets, etc.), we will use a way of measuring the size of a Java program that is insensitive to formatting factors. In particular, we define the following two notions:

  1. The size of a method is one more than the number of statements in the body of the method. The extra one counts the "declaration header" of the method as a statement.
  2. The size of a class is the sum of the sizes of all the methods in the class.

For instance, the size of the jump() method described above is 7, while the three methods jumpAndTurnRight(), jumpAndTurnLeft(), and jumpAndTurn180() each have size 3. So these four methods contribue 16 to the size of the FontBuggle class.

To enter the contest, all you need do is calculate the size of your FontBuggle class and write it on your problem set cover sheet.

We would like to point out that, while making your program shorter is fun and may be a helpful exercise, in general it should not be your goal to make a program shorter. Shorter programs often lack clarity, and since programs are written not only for machines to execute, but also for humans to read, clarity is a far more important goal!

Some rules/hints: