You are on page 1of 9

Mehran Sahami Handout #11

CS 106A October 5, 2007


Simple Programming Patterns
Based on a handout by Eric Roberts

This handout summarizes some of the most common programming patterns that you will
encounter in Java. Each of these patterns is covered in more detail in Chapters 2, 3, or 4
of the textbook, but it's good to have them in a simple handy reference as well.

The first set of patterns involves getting data in and out of the computer, which provide
the necessary support for the input and output phases of a typical programming task. The
patterns you use depend on the type of value, as shown in the following table:

Type Declaration Input pattern
Integer
int YDU = YDOXH; YDU = readInt("SURPSW");
Floating-point
double YDU = YDOXH; YDU = readDouble("SURPSW");
String
String YDU = YDOXH; YDU = readLine("SURPSW");

The following patterns are useful in calculations:

English 1ava (long form) 1ava (shorthand form)
Add \ to [.
x = x + y; x += y;
Subtract \ from [.
x = x - y; x -= y;
Add 1 to [ (increment [).
x = x + 1; x++;
Subtract 1 from [ (decrement [).
x = x - 1; x--;

The most helpful patterns, however, encompass programming operations on a larger scale
and help you establish the overall strategy of a program. The most important ones are
described in the next few sections.

The repeat-N-times pattern: (page 101)
This pattern is the same as it was in Karel and is used for the same purpose.

for (int i = 0; i < 1; i++) {
VWDWHPHQWVWREHUHSHDWHG
}

In Java, however, you are allowed to use the value of the index variable i in the body of
the loop.

The read-until-sentinel pattern: (page 102)
This pattern is useful whenever you need to read in values until the user enters a
particular value to signal the end of input. Such values are called sentinels.

while (true) {
SURPSWXVHUDQGUHDGLQDYDOXH
if (value == VHQWLQHO) break;
UHVWRIERG\
}
http://technicalsupportindia.blogspot.com/
id9104875 pdfMachine by Broadgun Software - a great PDF writer! - a great PDF creator! - http://www.pdfmachine.com http://www.broadgun.com
Mehran Sahami Handout #12!
CS 106A October 5, 2007!
Control Statements!
Based on a handout by Eric Roberts!
!
This handout oIIers some additional notes on Java`s control statements (described more!
Iully in Chapter 4 oI the textbook) that emphasize the important concepts. It also!
describes a programming problem making use oI various control structures.!
!
To write programs, you need to understand control statements Irom two perspectives: you!
must have a holistic sense oI when to use them and why, but you must also learn to!
understand the reductionistic details. For this big-picture perspective, you can rely to a!
large extent on your experience Irom Karel:!
!
II you want to test a condition that requires an!if!statement in Karel, you need the!if!
statement in Java.!
II you would use the! while! or! for! statement in Karel, you will presumably use the!
same statement Iorm in Java.!
!
The other holistic point that is essential about control statements is that the control line!
is conceptually independent Irom the body. Thus, iI you see a construct like!
!
for (int i = 0; i < 10; i++) {! ! 'SRXVSPPMRI!
! WXEXIQIRXW! ! &SH]!
}!
!
the statements in the body will be repeated Ior each oI the values oI! i!Irom 0 to 9. It!
doesn`t matter at all what those statements are.!
!
&SSPIERHEXE!
Another important topic is that oI the data type!boolean, which is the means by which!
Java programs ask questions. In Karel, the counterparts to! boolean! are the conditions!
such as! frontIsClear()! or! beepersPresent(). In Java, the range oI available!
conditions is much richer and involves the relational operators and the logical operators!
(both covered on page 78 oI textbook). The most important lessons to take Irom these!
sections are:!
!
Watch out Ior conIusing! =! (assignment) with! ==! (equality). This Ieature oI several!
programming languages (including C, C, and Java) has probably caused more bugs!
than any other.!
Be careIul to understand both the interpretation and the evaluation order oI the logical!
operators!&&!(and),!||!(or), and!!!(not).!
!
The time you put into making sure you understand!boolean!data now will pay Ior itselI!
many times over when the programs get more complicated later in the quarter.!
!
!
http://technicalsupportindia.blogspot.com/
! 2 !
'LIGOIVFSEVHTVSFPIQ!
Create a!GraphicsProgram!subclass that draws a checkerboard in the graphics window.!
The number oI rows and columns are given by the named constants!NROWS!and!NCOLUMNS,!
and the squares should be sized so that they Iill the vertical space. For example, iI!NROWS!
and!NCOLUMNS!are both 8, running this program should produce the Iollowing output:!
!
!
!
+VETLMGWPMFVEV]HSGYQIRXEXMSR!
The!javadoc!documentation Ior the ACM libraries is available under the 'Links section!
oI the CS 106A home page. Also, the methods in Figure 1 will help with the assignment.!
!
Figure 1. Some usefuI methods in acm.graphics!
Constructors!
! new GLabel(String text)! SV! new GLabel(String text, double x, double y)!
Creates a new!GLabel!obiect: the second Iorm sets its location as well.!
!
! new GRect(double x, double y, double width, double height)!
Creates a new!GRect!obiect: the!x!and!y!parameters can be omitted and deIault to 0.!
!
! new GOval(double x, double y, double width, double height)!
Creates a new!GOval!obiect: the!x!and!y!parameters can be omitted and deIault to 0.!
!
! new GLine(double x1, double y1, double x2, double y2)!
Creates a new!GLine!obiect connecting (x1,!y1) and (x2,!y2).!
!
Methods common to aII graphicaI object!
! void setLocation(double x, double y)!
Sets the location oI this obiect to the speciIied coordinates.!
!
! void move(double dx, double dy)!
Moves the obiect using the displacements!dx!and!dy.!
!
! double getWidth()!
Returns the width oI the obiect.!
!
! double getHeight()!
Returns the height oI the obiect.!
!
! void setColor(Color c)!
Sets the color oI the obiect.!
!
Methods avaiIabIe for GRect and GOvaI onIy!
void setFilled(boolean fill)!
Sets whether this obiect is Iilled (true!means Iilled,!false!means outlined).!
boolean isFilled()!
Returns!true!iI the obiect is Iilled.!
void setFillColor(Color c)!
Sets the color used to Iill this obiect. II the color is!null, Iilling uses the color oI the obiect.!
Methods avaiIabIe for GLabeI onIy!
! void setFont(String fontName)!
Sets the Iont, as described in Chapter 5.!
!
! double getAscent()!
Returns the height above the baseline.!
!
! ! !
under the 'Links section!
http://technicalsupportindia.blogspot.com/
! 3 !
7SPYXMSRXSXLI'LIGOIVFSEVHTVSFPIQ!
!
!
!
/*!
! * File: Checkerboard.java!
! * -----------------------!
! * This program draws a checkerboard.!
! */!
!
import acm.graphics.*;!
import acm.program.*;!
!
/*!
! * This class draws a checkerboard on the graphics window.!
! * The size of the checkerboard is specified by the!
! * constants NROWS and NCOLUMNS, and the checkboard fills!
! * the vertical space available.!
! */!
!
public class Checkerboard extends GraphicsProgram {!
!
! /* Number of rows */!
! private static final int NROWS = 8;!
!
! /* Number of columns */!
! private static final int NCOLUMNS = 8;!
!
! /* Runs the program */!
! public void run() {!
! int sqSize = getHeight() / NROWS;!
! for (int i = 0; i < NROWS; i++) {!
! for (int j = 0; j < NCOLUMNS; j++) {!
! int x = j * sqSize;!
! int y = i * sqSize;!
! GRect sq = new GRect(x, y, sqSize, sqSize);!
! sq.setFilled(((i + j) % 2) != 0);!
! add(sq);!
! }!
! }!
! }!
}!
!
!
!
!
http://technicalsupportindia.blogspot.com/
Mehran Sahami Handout #12
CS 106A October 5, 2007
Assignment #2: Simple Java Programs
Due: 3:15pm on Monday, October 15th
Based on a handout by Eric Roberts

Your job in this assignment is to write programs to solve each of these six problems.

1. Write a GraphicsProgram subclass that draws a pyramid consisting of bricks
arranged in horizontal rows, so that the number of bricks in each row decreases by
one as you move up the pyramid, as shown in the following sample run:



The pyramid should be centered at the bottom of the window and should use
constants for the following parameters:

BRICK_WIDTH The width of each brick (30 pixels)
BRICK_HEIGHT The height of each brick (12 pixels)
BRICKS_IN_BASE The number of bricks in the base (14)

The numbers in parentheses show the values for this diagram, but you must be able
to change those values in your program.
http://technicalsupportindia.blogspot.com/
2

2.
archery target or, if you prefer commercial applications, a logo for a national
department store chain that looks like this:



This figure is simply three GOval objects, two red and one white, drawn in the correct
order. The outer circle should have a radius of one inch (72 pixels), the white circle
has a radius of 0.65 inches, and the inner red circle has a radius of 0.3 inches. The
figure should be centered in the window of a GraphicsProgram subclass.


3. Write a GraphicsProgram subclass that draws a partial diagram of the acm.program
class hierarchy, as follows:



The only classes you need to create this picture are GRect, GLabel, and GLine. The
major part of the problem is specifying the coordinates so that the different elements
http://technicalsupportindia.blogspot.com/
3
of the picture are aligned properly. The aspects of the alignment for which you are
responsible are:

The ZLGWK and KHLJKW of the class boxes should be specified as named constants
so that they are easy to change.
The labels should be centered in their boxes. You can find the width of a label by
calling label.getWidth() and the height it extends above the baseline by calling
label.getAscent(). If you want to center a label, you need to shift its origin by
half of these distances in each direction.
The connecting lines should start and end at the center of the appropriate edge of
the box.
The entire figure should be centered in the window.


4. In high-school geometry, you learned the Pythagorean theorem for the relationship of
the lengths of the three sides of a right triangle:

D
2
+ E
2
= F
2


which can alternatively be written as:

F =
b a
2 2


Most of this expression contains simple operators covered in Chapter 3. The one
function Math.sqrt. For example, the statement

double y = Math.sqrt(x);

sets y to the square root of x.

Write a ConsoleProgram that accepts values for a and b as ints and then calculates
the solution of c as a double. Your program should be able to duplicate the
following sample run:


http://technicalsupportindia.blogspot.com/
4

5. Write a ConsoleProgram that reads in a list of integers, one per line, until a sentinel
value of 0 (which you should be able to change easily to some other value). When the
sentinel is read, your program should display the smallest and largest values in the
list, as illustrated in this sample run:



Your program should handle the following special cases:

If the user enters only one value before the sentinel, the program should report
that value as both the largest and smallest.
If the user enters the sentinel on the very first input line, then no values have been
entered, and your program should display a message to that effect.

6. -prize-winning book *|GHO (VFKHU %DFK contains
many interesting mathematical puzzles, many of which can be expressed in the form
of computer programs. In Chapter XII, Hofstadter mentions a wonderful problem that
is well within the scope of the control statements from Chapter 4. The problem can
be expressed as follows:

Pick some positive integer and call it Q.
If Q is even, divide it by two.
If Q is odd, multiply it by three and add one.
Continue this process until Q is equal to one.

On page 401 of the Vintage edition, Hofstadter illustrates this process with the
following example, starting with the number 15:

15 is odd, so I make 3Q+1: 46
46 is even, so I take half: 23
23 is odd, so I make 3Q+1: 70
70 is even, so I take half: 35
35 is odd, so I make 3Q+1: 106
106 is even, so I take half: 53
53 is odd, so I make 3Q+1: 160
http://technicalsupportindia.blogspot.com/
5
160 is even, so I take half: 80
80 is even, so I take half: 40
40 is even, so I take half: 20
20 is even, so I take half: 10
10 is even, so I take half: 5
5 is odd, so I make 3Q+1: 16
16 is even, so I take half: 8
8 is even, so I take half: 4
4 is even, so I take half: 2
2 is even, so I take half: 1

As you can see from this example, the numbers go up and down, but eventually at
least for all numbers that have ever been tried comes down to end in 1. In some
respects, this process is reminiscent of the formation of hailstones, which get carried
upward by the winds over and over again before they finally descend to the ground.
Because of this analogy, this sequence of numbers is usually called the +DLOVWRQH
VHTXHQFH although it goes by many other names as well.

Write a ConsoleProgram that reads in a number from the user and then displays the
showing the number of steps taken to reach 1. For example, your program should be
able to produce a sample run that looks like this:



The fascinating thing about this problem is that no one has yet been able to prove that
it always stops. The number of steps in the process can certainly get very large. How
many steps, for example, does your program take when Q is 27?
http://technicalsupportindia.blogspot.com/

You might also like