some notes about the labs

The if Statement

  1. Create a new Robot with a method which will pick up a beeper if one is present, otherwise it will move forward one square. Write a test program that will create a world and place your new robot in the world. Execute your test method for each case, i.e. when there is a beeper in the cell with a robot and when there is no beeper in the cell.

  2. Create a Robot with a method which will always turn to face north and then move forward one square. Write a Test program which creates a World and place four of your Robots on the world, each facing a different direction. Verify that the robots all do as required.

    Which robot executes the most instructions? Which executes the fewest instructions?

  3. Consider the following Robot

    IfRobot.java
    public class IfRobot extends Robot
    {
       void go()
       {
          if(beeperPresent())
          {
             pickBeeper();
             move();
          }
          else
          {
             turnLeft();
             move();
          }
       }
    }

    Can the statements in the go() method be rearranged so that the same effect is achieved using fewer statements?

    Hint: the move() is executed whether or not a beeper is present, could it be moved outside the if statement? If you do rearrange the code, ensure that it still does the same thing.

  4. Consider the following three Robot definitions

    BeeperSeeker1.java
    public class BeeperSeeker1 extends Robot
    {
       void go()
       {
          if(!beeperPresent())
          {
             move();
          }
          else
          {
             pickBeeper();
          }
       }
    }

    BeeperSeeker2.java
    public class BeeperSeeker2 extends Robot
    {
       void go()
       {
          if(!beeperPresent())
          {
             move();
          }
          if(beeperPresent())
          {
             pickBeeper();
          }
       }
    }

    BeeperSeeker3.java
    public class BeeperSeeker3 extends Robot
    {
       void go()
       {
          if(beeperPresent())
          {
             pickBeeper();
          }
          if(!beeperPresent())
          {
             move();
          }
       }
    }

    Their go() methods are slightly different. Will they always do the same thing? Try and imagine a situation where they would act differently. If you can't imagine, then check this test.

  5. Optional Problem
    Assume that a robot is in a cell with either one or two beepers. Write a new method that commands the robot to face north if it is started in a cell with one beeper and to face south if it is started in a cell with two beepers. Besides facing the robot in the required direction, after it has executed this method there must be no beepers left in the cell. Name this method findNextDirection.