Download presentation
1
Karel J Robot Chapter 5
2
Chapter 5 Conditional Statements
Flavor 1: if ( <some boolean expression> ) { <some instruction list> } For now: these are method invocations (see next slide) Chapter 5
3
IF frontIsClear(); nextToABeeper(); nextToARobot(); facingNorth();
“predicates” either T or F IF frontIsClear(); nextToABeeper(); nextToARobot(); facingNorth(); facingSouth(); facingEast(); facingWest(); anyBeepersInBeeperBag(); if ( ) { … } Robot Chapter 5
4
again, you don’t write this class
Robot Class public class Robot extends UrRobot { public boolean frontIsClear() {…} public boolean nextToABeeper() {…} public boolean nextToARobot() {…} etc… } Now I have a brain! again, you don’t write this class Chapter 5
5
Examples if (frontIsClear() ) { move(); // no danger of hitting wall }
if ( anyBeepersInBeeperBag() ) { putBeeper(); // no danger of error } Chapter 5
6
public boolean beeperIsToLeft() { turnLeft(); move();
MUST put world back in initial situation that it was in BEFORE the method was invoked public boolean beeperIsToLeft() { turnLeft(); move(); if ( nextToABeeper() ) turnLeft(); turnLeft(); move(); turnLeft(); return true; } turnLeft(); turnLeft(); move(); turnLeft(); return false; Chapter 5
7
Boolean Operators Karel (Java) Robot (&&, ||, !) if (! frontIsClear())
{ turnLeft(); } move(); Chapter 5
8
IF - ELSE Flavor 2: if ( <boolean expression> ) {
<statements> } else <statements – somewhat different> Chapter 5
9
IF – ELSE Simplifications
simplify: if ( frontIsClear() ) { return true; } return false; simplify: if ( frontIsClear() ) { return true; } else return false; Chapter 5
10
Simplify – bottom factoring
move(); move(); if ( facingSouth() ) { turnLeft(); move(); } else turnRight(); if ( facingSouth() ) { turnLeft(); } else turnRight(); move(); move(); move(); move(); Chapter 5
11
Simplify – top factoring
move(); if ( beeperOnLeft() ) { turnLeft(); } else turnRight(); if ( beeperOnLeft() ) { move(); turnLeft(); } else turnRight(); Chapter 5
12
no need to check for the same thing twice!
if ( facingNorth() ) { move(); pickTwoBeepers(); if (facingNorth()) turnLeft(); } if ( facingNorth() ) { move(); pickTwoBeepers(); turnLeft(); } Chapter 5
13
Chapter 5
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.