Pages

Wednesday, 8 June 2011

Mehran Sahami Handout #15A CS 106A October 10, 2007 Solutions for Section #2 Based on a handout by Eric Roberts


Mehran Sahami Handout #15A
CS 106A October 10, 2007
Solutions for Section #2
Based on a handout by Eric Roberts
1. The Fibonacci sequence
/*
* File: Fibonacci.java
* --------------------
* This program lists the terms in the Fibonacci sequence up to
* a constant MAX_TERM_VALUE, which is the largest Fibonacci term
* the program will display.
*/
import acm.program.*;
public class Fibonacci extends ConsoleProgram {
public void run() {
println("This program lists the Fibonacci sequence.");
int t1 = 0;
int t2 = 1;
while (t1 <= MAX_TERM_VALUE) {
println(t1);
int t3 = t1 + t2;
t1 = t2;
t2 = t3;
}
}
/* Defines the largest term to be displayed */
private static final int MAX_TERM_VALUE = 10000;
}
– 2 –
2. Drawing a robot face
/* File: RobotFace.java */
/* This program draws a robot face. */
import acm.graphics.*;
import acm.program.*;
import java.awt.*;
public class RobotFace extends GraphicsProgram {
/* Parameters for the drawing */
private static final int HEAD_WIDTH = 100;
private static final int HEAD_HEIGHT = 150;
private static final int EYE_RADIUS = 10;
private static final int MOUTH_WIDTH = 60;
private static final int MOUTH_HEIGHT = 20;
public void run() {
addFace(getWidth() / 2, getHeight() / 2);
}
/* Adds the entire face centered at (cx, cy) */
private void addFace(double cx, double cy) {
addHead(cx, cy);
addEye(cx - HEAD_WIDTH / 4, cy - HEAD_HEIGHT / 4);
addEye(cx + HEAD_WIDTH / 4, cy - HEAD_HEIGHT / 4);
addMouth(cx, cy + HEAD_HEIGHT / 4);
}
/* Adds the head centered at (cx, cy) */
private void addHead(double cx, double cy) {
double x = cx - HEAD_WIDTH / 2;
double y = cy - HEAD_HEIGHT / 2;
GRect head = new GRect(x, y, HEAD_WIDTH, HEAD_HEIGHT);
head.setFilled(true);
head.setFillColor(Color.GRAY);
add(head);
}
/* Adds an eye centered at (cx, cy) */
private void addEye(double cx, double cy) {
double x = cx - EYE_RADIUS;
double y = cy - EYE_RADIUS;
GOval eye = new GOval(x, y, 2 * EYE_RADIUS, 2 * EYE_RADIUS);
eye.setFilled(true);
eye.setColor(Color.YELLOW);
add(eye);
}
/* Adds a mouth centered at (cx, cy) */
private void addMouth(double cx, double cy) {
double x = cx - MOUTH_WIDTH / 2;
double y = cy - MOUTH_HEIGHT / 2;
GRect mouth = new GRect(x, y, MOUTH_WIDTH, MOUTH_HEIGHT);
mouth.setFilled(true);
mouth.setColor(Color.WHITE);
add(mouth);
}
}

0 comments:

Post a Comment

Search This Blog