Prelab 5: methods & Conditionals

Reading

New Constructs

Conditional Execution: if

Used when something is to be done once or not at all
if ( << boolean-expression >> )
{
  <<statements to repeat if boolean-expression evaluates to true>>
}

1. Describe the behavior if it executes the following code.

if (karel.besideThing()) { karel.pickThing(); }



Conditional Loop: while

Used when the number of repetitions depends on a condition being met.
while ( << boolean-expression >> )
{
  <<statements to repeat while boolean-expression evaluates to true >>
}

2. Describe the behavior of karel if it executes the following code.

while (karel.frontIsClear()) { karel.move(); }






Suppose you are given the following problem:
Assume that your robot is positioned at (0,0) facing East. Write a method that makes the robot walk forward 5 steps. It must pick up any Things it encounters and then be labeled as "DONE."
public void walk_five() { int stepCount = 0; while (step_count < 5) { if (canPickThing()) { pickThing(); } move(); stepCount = stepCount+1; } setLabel("DONE"); } 3. Does this method correctly solve the problem? Why or why not?




4. All methods in Java are inside of some sort of class. What kind of class definition must the class be in? Give the class header.





5. As you can see, the algorithm is fairly simple. What particular information were we given in this particular problem that made the algorithm easy to formulate? Would the problem be harder if we had less information? Why or why not? Could you think of additional information that would lead to an even simpler algorithm?




Escaping from a box

6. Consider a robot with walls on some of the sides of the intersection. Write a method called escape that takes the robot out of the intersection if possible.
Initial Situation Final Situation
public void escape() {

Submitting

Bring your answers with you to lab. You need to turn in your answers at the beginning of lab to receive credit.
Adapted from Byron Weber Becker and Tammy Bailey.
Comments?