| 1 | Consider a program that must drive a robot forward some distance and then turn the robot 90-degrees to face a target. As the program runs, it spends time in at least two states: |
| 2 | * Driving Forward |
| 3 | * Turning |
| 4 | It may remain in each state for a considerable amount of time. A useful way to model this in software is using a '''State Machine'''. |
| 5 | |
| 6 | As the name implies, a State Machine is a program that has stateful behavior, meaning that what it does at any given moment depends on its current state. We could model the above sequence of states with this program: |
| 7 | {{{ |
| 8 | public class StateMachine { |
| 9 | private enum State { START, FORWARD, TURN, STOP }; |
| 10 | |
| 11 | public static void main(String args[]) { |
| 12 | State state = State.START; |
| 13 | while (true) { |
| 14 | switch (state) { |
| 15 | case START: |
| 16 | System.out.println("START->FORWARD..."); |
| 17 | state = State.FORWARD; |
| 18 | break; |
| 19 | case FORWARD: |
| 20 | System.out.println("FORWARD->TURN..."); |
| 21 | state = State.TURN; |
| 22 | break; |
| 23 | case TURN: |
| 24 | System.out.println("TURN->STOP..."); |
| 25 | state = State.STOP; |
| 26 | break; |
| 27 | case STOP: |
| 28 | default: |
| 29 | // finished..nothing to do |
| 30 | } |
| 31 | } |
| 32 | } |
| 33 | } |
| 34 | }}} |
| 35 | |
| 36 | This program introduces a new type of variable called an enumeration ('''enum'''). An enum is a variable that can hold one of the values you specify when you declare it. For example: {{{ enum Color { RED, GREEN, BLUE }; }}} In this example, we've enumerated the states the robot can be in: starting, driving forward, turning, and stopped. |
| 37 | |
| 38 | The program also introduces the '''switch''' statement which is another type of conditional like ''if ,else if, else''. With a switch statement, the condition is the value of a variable; execution jumps to the ''case'' that matches the variable's value and proceeds forward from there until a ''break'' statement is encountered which exits the switch block. If there is no case statement matching the variable's value, the '''default''' case is executed. |
| 39 | |
| 40 | Run the program in the debugger and observe how the state variable and switch statement interact. |
| 41 | |
| 42 | Notice that: |
| 43 | * The current state is stored in a ''state variable'' named '''state''' in this program. |
| 44 | * The case matching the current state is run each time we go through the loop |
| 45 | * The program can stay in any state for as long as needed and explicitly advances to the next state when it's ready. |