Advertisement
dhaese

MidpointFindingKarel recursive

Nov 20th, 2011
2,260
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.12 KB | None | 0 0
  1. /*
  2.  * File: MidpointFindingKarel.java
  3.  * -------------------------------
  4.  * The MidpointFindingKarel subclass places a single beeper on the
  5.  * corner closest to the center of 1st Street(or on one of the two
  6.  * central corners if 1st Street has an even number of corners).
  7.  * See further description in assignment #1 handout.
  8.  */
  9.  
  10. import stanford.karel.*;
  11.  
  12. public class MidpointFindingKarel extends SuperKarel {
  13.  
  14.     public void run() {
  15.         if (frontIsClear()) {
  16.             moveToMidpoint();
  17.         }
  18.         putBeeper();
  19.     }
  20.    
  21.     private void moveToMidpoint() { // starting east, for every two corners Karel moves east, after reaching the east end of the street, Karel moves back one corner to the west.
  22.         if (facingEast()) { // move up to two corners to the east, if possible
  23.             move();
  24.             if (frontIsClear()) {
  25.                 move();
  26.                 if (frontIsClear()) {
  27.                     moveToMidpoint(); //method calls itself
  28.                 } else {
  29.                     turnAround(); // turn around, if end of street in the east is reached
  30.                 }
  31.             } else {
  32.                     turnAround(); // turn around, if end of street in the east is reached
  33.             }
  34.         }
  35.         move(); // move back one corner to the west
  36.     }
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement