{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

32-midterm-soln

# 32-midterm-soln - Mehran Sahami CS 106A Handout#32 November...

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

Mehran Sahami Handout #32 CS 106A November 5, 2007 Solutions to Midterm Exam Problem 1: Karel the Robot (15 points) /* * File: TreasureHuntKarel.java * ---------------------------- * This program has Karel run a treasure hunt. */ import stanford.karel.*; public class TreasureHuntKarel extends SuperKarel { public void run() { /* Continue treasure hunt until we face wall (by treasure). We * are guaranteed not to encounter a wall until we reach treasure. */ while (frontIsClear()) { faceCorrectDirection(); moveToNextPile(); } } /* Turns Karel until he is facing East */ private void faceEast() { while (notFacingEast()) { turnLeft(); } } /* To face the correct direction based on a clue represented by a * pile of beepers, we first face East and then make one left turn * for each beeper in the pile. */ private void faceCorrectDirection() { faceEast(); while (beepersPresent()) { pickBeeper(); turnLeft(); } } /* Move forward until you reach next clue or treasure (pile of beepers) */ private void moveToNextPile() { while (noBeepersPresent()) { move(); } } }

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

View Full Document
Problem 2: Simple Java expressions, statements, and methods (15 points) (2a) 7 / ('C' - 'A') 3 4 > 5 || 3 % 1 == 0 && 6 * 3 > 19 false ('b' - 'a') + "a" "1a" (2b) What output is printed by the following program: First result: 19 Second result: 4 Problem 3: Simple Java program using the random number library (20 points) /* * File: CoinToss.java * ------------------- * Number of times to toss a coin until it comes up heads 3 times in a row. */ import acm.program.*; import acm.util.*; public class CoinToss extends ConsoleProgram { private static final int NUM_CONSECUTIVE = 3; public void run() {
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}