110 likes | 497 Views
Karel. Chapter 5. A new class!. 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. Robot methods. frontIsClear () – boolean , returns true or false checks if immediate front has wall or not
E N D
Karel Chapter 5
A new class! • 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
Robot methods • 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
The If Method • Karel can make decisions for himself! • Syntax: • if(condition) • { <do some action>} • Example: • if(frontIsClear()) • { move();}
If method • 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”
If-else • Useful if you want only 1 of 2 alternatives • Ex) if(frontIsClear()) • { • move(); • } //note – bracket is closed • Else • { • putBeeper(); • }
Nested if’s • 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
Nested if’s • 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
transformations • Test reversal • Bottom factoring • Top factoring • Redundant test factoring • All on pages 123-126 see how these work!
Before problem set • 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
Problem set • 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