ICE 4 Worksheet.doc

advertisement
BIT 115 – LECTURE 4 – ICE PARTS 1 and 2
NAME: ____________________________________________________
Making Decisions: If, While, If/Else Statements
Part 1: Boolean Expressions
Evaluate the following Boolean expressions for a Robot. Assume the robot is on intersection (1, 5)
facing North. There is a Wall immediately in front of it. In each case your answer will be either true
or false. Highlight or circle the correct answer.
a.
this.getAvenue() > 0 TRUE or FALSE
b.
this.getAvenue() <= 5 TRUE or FALSE
c.
this.getStreet() != 1 TRUE or FALSE
d.
!(this.getStreet() == 1) TRUE or FALSE
e.
this.frontIsClear() TRUE or FALSE
f.
!this.frontIsClear() TRUE or FALSE
g.
!!this.frontIsClear() TRUE or FALSE (notice there are two !!)
h.
this.frontIsClear() == false TRUE or FALSE
Page 1
Part 2: Creating New Methods
1. Write a pair of methods, as follows:
a) carryExactlyEight ensures a robot is carrying exactly eight things in its
backpack. Assume the robot is on an intersection with at least eight things that
can be picked up.
HINT: countThingsInBackpack()
public void carryExactlyEight()
{ // put down extra things, if holding more than 8
while(
) // <-- code
{
this.putThing();
}
// pick up things if we didn’t start with 8
while(
) // <-- code
{
this.pickThing();
}
}
b) Generalize carryExactlyEight above to carryExactly. The new method will take
a parameter specifying how many Things the robot should carry.
HINTS: countThingsInBackpack(), num, or look at the NumTest.java demo file
public void carryExactly(int num)
{ // put down extra things, if any
while(
{
this.putThing();
}
) // <-- code
// pick up things if we didn’t start with num
while(
) // <-- code
{
this.pickThing();
}
}
Page 2
2. Write a new robot method, faceNorth. A robot that executes faceNorth will turn so
that getDirection returns Direction.NORTH.
a) Write faceNorth so that the robot turns left until it faces north. Use several if
statements.
HINTS: getDirection(), Direction.EAST, Direction.SOUTH, Direction.WEST
public void faceNorth()
{
if (
{
this.turnLeft();
}
if (
{
) //<-- code
) // <-- code
this.turnLeft();
this.turnLeft();
}
if (
{
) // <-- code
this.turnLeft();
this.turnLeft();
this.turnLeft();
}
}
b) Write faceNorth so that the robot turns left until it faces north. Use a while
statement.
HINTS: getDirection(), Direction.NORTH
public void faceNorth()
{
while (
{
this.turnLeft();
}
}
Page 3
) // <-- code
Part 3: If-Else
Return to http://faculty.cascadia.edu/cduckett/bit115 and follow the In-Class Exercises 4
under the If, While, If/Else Statements (Making Decisions) section.
Keep On Codin’!
Page 4
Download