Conditional Statements or ELSE
if ( <some boolean expression> )
{
<some instruction list>
<to execute when boolean expression is true>
}
else
{
<some instruction list>
<to execute when boolean expression is false>
}
karel_part3_ifElse
1
Indenting by example
• How to properly indent while writing if/else structures by example!
public void someMethod()
{
if ( <someBooleanExpression> )
{
codeGoesHere();
allAdditionalCodeLinesUp();
soAllFirstLettersAreInTheSameColumn();
}
else
{
sameSpacingAfterTheElse();
asWhatWasUsedAfterTheIf();
}
untilAnotherIfStatementIsEncountered();
}
karel_part3_ifElse
2
A word about indenting
How to properly indent while writing if structures!
• Every time an if is used, each line after the curly bracket, {should be
spaced over to the right a constant amount (say 3 spaces).
– To simplify, the first letter of each method/line-of-code should be under
the ( in the if statement.
• The same spacing is used between the brackets that follow the else
• When the if/else is terminated ( closing curly bracket } ), the
following lines of code are moved left by the same number of spaces
used above (3 was used above).
– To simplify, the first letter of each method/line-of-code should be under
the i in the if statement.
Please review previous slide
karel_part3_ifElse
3
A Final Indenting example
if ( frontIsClear())
{
move();
turnLeft();
}
else
{
turnLeft();
if ( frontIsClear())
{
move();
}
}
turnLeft();
karel_part3_ifElse
4
Sample Code with Objects
if (karel.frontIsClear() )
{
karel.move(); // no danger of hitting wall
}
else
{
karel.turnLeft();
}
karel_part3_ifElse
5
Sample Method
public void moveOrTurnLeft()
{
if ( frontIsClear() )
{
move();
// no danger of hitting wall
}
else
{
turnLeft();
}
}
karel_part3_ifElse
6
Simplify – bottom factoring
if ( facingSouth() )
{
turnLeft();
move();
}
else
{
turnRight();
move();
}
if ( facingSouth() )
{
turnLeft();
}
else
{
turnRight();
}
move();
karel_part3_ifElse
7
Simplify – top factoring
if ( beeperOnLeft() )
{
move();
turnLeft();
}
else
{
move();
turnRight();
}
karel_part3_ifElse
8
Simplify – top factoring
move();
// changes value of boolean expression
if ( beeperOnLeft() )
{
turnLeft();
}
else
{
turnRight();
}
karel_part3_ifElse
9
being redundant again and again
and againha ha
if ( facingNorth() )
{
move();
pickTwoBeepers();
if (facingNorth())
{
turnLeft();
}
}
if ( facingNorth() )
{
move();
pickTwoBeepers();
turnLeft();
}
karel_part3_ifElse
10
Your Assignment
• Implementing the followAllBreadCrumbs
method declared in HanselAndGretelRobot
class.
• The followAllBreadCrumbs method will
invoke the followBreadCrumb method 56
times.
• No method may contain more than seven
commands.
• You will need to implement the
followBreadCrumb method as described in
handout (Karel_part2_ifElse.doc) for details.
karel_part3_ifElse
11
© Copyright 2026 Paperzz