If / Else Structures


Topics
If / Else

Note: if your students have programed before you should skip over the lessons on if/else and loops.

Handouts
Challenges - Solutions

Lesson
Begin this lesson by explaining the general concept of an if/else (or Fork) statement. One of the easier ways to do this is by using real life examples. If it is sunny out put on your sunglasses else it is raining so put up an umbrella. The if/else is a decision based on the way things are right now.

  Note: The program checks the touch sensor the moment it starts. So if you want the touch sensor to register as pushed in, you have to push it in before running the program.

Here is an example program to start with:
  import josx.platform.rcx.*;

/**
* plays a buzzing sound if the robot starts with the touch
* sensor pressed in. Otherwise it starts with a double beep
**/

public class IfExample {

    public static void main (String[] args) throws Exception {
        // activate sensor
        Sensor.S1.setTypeAndMode (1, 0x20);
        Sensor.S1.activate();

        // determin if sensor is pushed in or not
        if(Sensor.S1.readBooleanValue()) {
            Sound.buzz();
        }
        else {
            Sound.twoBeeps();
        }

        // wait for a second to complete the sound
        Thread.sleep(1000);
    }
}