Title: CH5 Conditional Statements
1CH5 Conditional Statements
- Flavor 1
- if ( ltsome boolean expressiongt )
-
- ltsome instruction listgt
For now these are method invokations (see next
slide)
2IF
predicates either Tor F
frontIsClear() nextToABeeper() nextToARobot() f
acingNorth() facingSouth() facingEast() facingW
est() anyBeepersInBeeperBag()
Robot
Lets check the API to see our options
3Robot Class
- public class Robot extends UrRobot
-
- public boolean frontIsClear()
- public boolean nextToABeeper()
- public boolean nextToARobot()
- etc
Now I have a brain!
again, you dont write this class
4Examples
- if ( karel.frontIsClear() )
-
- karel.move() // no danger of hitting wall
-
if ( karel.anyBeepersInBeeperBag()
) karel.putBeeper() // no danger of error
5Extending Robot
- public class SmartBot extends Robot
-
- public boolean beeperIsToLeft()
- public boolean twoBeepersOnCornerOrMore()
- public void faceEast()
Draw the Inheritance Hierarchy
6- public boolean beeperIsToLeft()
-
- turnLeft()
- move()
- if ( nextToABeeper() )
-
- turnLeft() turnLeft() move()
turnLeft() return true -
- turnLeft() turnLeft() move() turnLeft()
- return false
7you write twoBeepersOnCornerOrMore()it belongs
to the SmartBot classnote you may have to nest
if statements
8you write faceEast()it belongs to the SmartBot
class
9Paying Attention?
- For the last several slides, Ive lead you
somewhat astray. By now (Im hoping) someone has
pointed out that our Inheritance Structure looks
likes this
What annoying thing (should have) happened to you
while coding the last few examples?
Yep, you wrote (or wanted to) turnRight() and
maybe even turnAround() AGAIN! ANNOYING!
Solution(s)?
10Boolean Operators
- Same as C (, , !)
- Karel (Java) Robot (, , !)
- if (! frontIsClear())
-
- turnLeft()
-
- move()
11 and (no, I didnt stutter)
- Write this method
- /
- _at_returns true if there is at least
- one beeper on both sides of bot,
- false otherwise
- /
- public boolean isBeepOnLeft_And_BeepOnRight()
- Assume that the class youre writing this for has
SmartBot as its superclass (the one we just
suggested). It may help to look at the
inheritance tree again.
12IF - ELSE
- Flavor 2
- if ( ltboolean expressiongt )
-
- ltstatementsgt
-
- else
-
- ltstatements somewhat differentgt
13IF ELSE Simplifications
- simplify
- if ( frontIsClear() )
-
- return true
-
- else
-
- return false
-
14Simplify
- if ( ! leftIsBlocked() )
-
- return true
-
- else
-
- return false
15Simplify
- if ( leftIsBlocked() )
-
- return false
-
- else
-
- return true
16Simplify bottom factoring
move()
move()
- if ( facingSouth() )
-
- turnLeft()
- move()
-
- else
-
- turnRight()
- move()
if ( facingSouth() ) turnLeft() else turn
Right()
move()
move()
move()
move()
17Simplify top factoring
- if ( beeperOnLeft() )
-
- move()
- turnLeft()
-
- else
-
- move()
- turnRight()
18being redundant again and again and againha ha
- if ( facingNorth() )
-
- move()
- pickTwoBeepers()
- if (facingNorth())
-
- turnLeft()
-