Chapter 5
We’ve been using UrRobot – knows only 5 things Let’s now use a new type of Robot: Robot! i.e. – public class MileMover extends Robot
frontIsClear () – boolean, returns true or false checks if immediate front has wall or not nextToABeeper() – boolean checks if corner it is on has a beeper nextToARobot() – boolean facingNorth() – … south, east, west anyBeepersInBeeperBag() All methods are booleans!!!! Still has all of UrRobot’s methods
Karel can make decisions for himself! Syntax: if(condition) { } Example: if(frontIsClear()) { move();}
The parameter of the method (inside the brackets): Any statement that will mean: if(true) or if(false) Many ways to say true or false: if(frontIsClear()) – if front is clear If(! frontIsClear()) – if front is not clear ! exclamation point means “not”
Useful if you want only 1 of 2 alternatives Ex) if(frontIsClear()) {{ move(); } //note – bracket is closed Else {{ putBeeper(); }}
Necessary when multiple conditions need to be tested Ex) if(nextToABeeper()) { if(frontIsClear()) {pickBeeper(); move(); }} }} good idea to only limit nested if statements to 2 – 3 nests
What if: If(facingWest()) { if(frontIsClear()) { if (nextToABeeper()) { if (nextToARobot()) }}} We can fix this:: If(facingWest() && nextToABeeper() && nextToARobot()) Just use && (means AND) Also - || means OR These are called logical operators
Test reversal Bottom factoring Top factoring Redundant test factoring All on pages see how these work!
All programs we have done have an issue where the robot might have an error shut off (ex – running into a wall) Using our new methods, you should be able to reprogram the old programs to never have an error shut off try it with MileMover - reprogram move, pickBeeper, and putBeeper so they won’t have error shutoffs also – program Racer on page 123
Start to include comments: Each program should start with: //your name //AP Computer Science // Chapter 5, pr # // 10/##/09 Ch 5, #1, 2, 3, 6, 8, 9, 10, 11, 14 --large problem set, we will spend a lot of time in class on it, but make sure to program at home as well