32-midterm-soln

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

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

View Full Document Right Arrow Icon
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(); } } }
Background image of page 1

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

View Full DocumentRight Arrow Icon
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.*;
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 02/15/2010 for the course CS 106A taught by Professor Sahami,m during the Fall '08 term at Stanford.

Page1 / 5

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

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

View Full Document Right Arrow Icon
Ask a homework question - tutors are online