80 likes | 102 Views
Loops in Methods. And compound conditions. Overview. Loops can be used in the main method and in Jeroo methods They work the same way, only the syntax is different. Compound conditions allow for more complicated choices. Using a while loop in a Jeroo method.
E N D
LoopsinMethods And compound conditions
Overview • Loops can be used in the main method and in Jeroo methods • They work the same way, only the syntax is different. • Compound conditions allow for more complicated choices.
Using a while loop in a Jeroo method • Assume that a Jeroo named Kim is facing a line of flowers ahead. Have Kim pick all of those flowers, and stop as soon as there is no flower directly ahead. After picking all of the flowers, Kim should turn to the left. while( kim.isFlower(AHEAD) ){ kim.hop(); kim.pick(); } kim.turn(LEFT); How would this be written as part of a method?
RewrittenAs part of a method method pickRow(){ while(isFlower(AHEAD)) { hop(); pick(); } turn(LEFT); } The main program would be: method main(){ Jeroo kim = new Jeroo(); kim.pickRow(); }
Simple and Compound Conditions • A simple condition has one part. In the Jeroo language, a simple condition is formed by invoking a single sensor method. • Examples: • tiffany.isClear(RIGHT) • walter.isFacing(EAST) • A compound condition uses logical operators. The Jeroo language contains the three most commonly used logical operators: • ! (NOT)ie: !Tiffany.isClear(RIGHT) • && (AND)ie: Tiffany.isClear(RIGHT) && Tiffany.isClear(LEFT) • || (OR)ie: Tiffany.hasFlower() || Tiffany.isClear(AHEAD)
Compound condition examples • Boolean Expression (Java-style) & English Translation • ! bob.isNet(AHEAD) • There is not a net ahead of Bob • bob.hasFlower() && bob.isClear(LEFT) • Bob has at least one flower and there is nothing in the cell immediately to the left of Bob. • bob.isWater(AHEAD) || bob.isWater(RIGHT) • There is water ahead or to the right of Bob, or both • Notice the COMPLETE CONDITIONS on both sides of the OR • bob.isFacing(WEST) && ( ! bob.isNet(AHEAD) ) • Bob is facing west and there is no net ahead Use these examples to write compound conditions
Question: How do you know that a Jeroo has reached the end of the island? How do you say “ keep hopping until you reach the end of the island”? How do you say “keep removing nets until you reach the end of the island”? Answer: there is water ahead while (!isWater(AHEAD)) { hop(); } while(!isWater(AHEAD)) { // put the code here to // remove a net if there is one. } The Problem: Remove all the nets on Jessica’s right side as she crosses the island. Some questions: