/** * This is Java-like pseudocode that corresponds to the state machine shown * in FSM_example.pdf. */ public class StateExample { // Could do this with a group of constants instead public enum State { SLEEPING, BREAKFAST, TALKING, CLASS }; private State myState; // The state we're in /** * Take some new event and decide what to do next. Depends on the state * we're in. The tests for events are pseudocode (e.g. "event is alarm"), * as is some of the other code (e.g. "press snooze"). */ public void handleEvent() { switch (myState) { case SLEEPING: if (event is alarm) { if (snoozeCtr < 2) { press snooze snoozeCtr++; System.out.println("Just gonna snooze a bit..."); } else { snoozeCtr = 0; System.out.println("Guess I gotta get up..."); myState = State.BREAKFAST; } } else if (event is phone rings) { System.out.println("Hey! I was sleeping. Bye."); } else error break; case BREAKFAST: if (phone rings) { System.out.println("Sure, I'd be happy to talk"); myState = State.TALKING; } else if (time for class) { grab books; walk to class; System.out.println("Off to class I go..."); myState = State.CLASS; } else error break; case TALKING: if (I'm done || they're done) { System.out.println("Ok. Bye."); myState = State.BREAKFAST; } else error break; case CLASS: if (phone rings) { pretend it's not yours; System.out.println("Whose is that??"); } else if (class ends) { myState = next_place_to_wait; System.out.println("Off to somewhere else"); } else error break; default: System.out.println("Unexpected state!"); } } }