15a-section-2-solutions

# 15a-section-2-solutions - Mehran Sahami Handout#15A CS 106A...

This preview shows pages 1–3. Sign up to view the full content.

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Mehran Sahami Handout #15A CS 106A October 12, 2011 Solutions for Section #2 Portions of this handout by Eric Roberts and Jeremy Keeshin 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. Drawing centered text /* * File: CenteredText.java * ----------------------- * This programs displays a message centered in the graphics window. */ import acm.graphics.*; import acm.program.*; public class CenteredText extends GraphicsProgram { public void run() { GLabel label = new GLabel("CS106A rocks my socks!"); label.setFont("SansSerif-28"); double x = (getWidth() - label.getWidth()) / 2; double y = (getHeight() + label.getAscent()) / 2; label.setLocation(x, y); add(label); } } – 2 – 3. Drawing a robot face import java.awt.Color; import acm.program.*; import acm.graphics.*; /* * RobotFace.java * * This program draws a robot face using GRects and GOvals. * We make sure to define constants at the top of our program instead * of using magic numbers. We also write the program in terms of * reusable and general methods drawRectangle and drawCircle. */ public class RobotFace extends GraphicsProgram{ /* Parameters for the drawing */ private static final int HEAD_WIDTH = 150; private static final int HEAD_HEIGHT = 250; private static final int EYE_RADIUS = 10; private static final int MOUTH_WIDTH = 60; private static final int MOUTH_HEIGHT = 20; public void run(){ double cx = getWidth()/2; double cy = getHeight()/2; addHead(cx - HEAD_WIDTH/2, cy - HEAD_HEIGHT/2);...
View Full Document

{[ snackBarMessage ]}

### Page1 / 4

15a-section-2-solutions - Mehran Sahami Handout#15A CS 106A...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online