| 52 | |
| 53 | In computer science, we often draw '''state diagrams''' that represent the states and the transitions between states. Read about them [https://en.wikipedia.org/wiki/State_diagram here] |
| 54 | |
| 55 | Java is object oriented so its natural to model a state as an object. Consider (and run) the following program (from [https://rosettacode.org/wiki/Finite_state_machine here]) that models a vending machine; it's a complex program that will take some time to understand; try running it in the debugger: |
| 56 | {{{ |
| 57 | import java.util.*; |
| 58 | |
| 59 | public class StateMachine { |
| 60 | |
| 61 | private enum State { |
| 62 | // each state and its transitions (actions) |
| 63 | Ready(true, "Deposit", "Quit"), |
| 64 | Waiting(true, "Select", "Refund"), |
| 65 | Dispensing(true, "Remove"), |
| 66 | Refunding(false, "Refunding"), |
| 67 | Exiting(false, "Quiting"); |
| 68 | |
| 69 | State(boolean is_explicit, String... in) { |
| 70 | inputs = Arrays.asList(in); |
| 71 | explicit = is_explicit; |
| 72 | } |
| 73 | |
| 74 | State nextState(String input, State current) { |
| 75 | if (inputs.contains(input)) { |
| 76 | return map.getOrDefault(input, current); |
| 77 | } |
| 78 | return current; |
| 79 | } |
| 80 | |
| 81 | final List<String> inputs; |
| 82 | final static Map<String, State> map = new HashMap<>(); |
| 83 | final boolean explicit; |
| 84 | |
| 85 | // Map contains transitions, next state |
| 86 | static { |
| 87 | map.put("Deposit", State.Waiting); |
| 88 | map.put("Quit", State.Exiting); |
| 89 | map.put("Select", State.Dispensing); |
| 90 | map.put("Refund", State.Refunding); |
| 91 | map.put("Remove", State.Ready); |
| 92 | map.put("Refunding", State.Ready); |
| 93 | } |
| 94 | } |
| 95 | |
| 96 | public static void main(String[] args) { |
| 97 | Scanner sc = new Scanner(System.in); |
| 98 | State state = State.Ready; |
| 99 | |
| 100 | while (state != State.Exiting) { |
| 101 | System.out.println(state.inputs); |
| 102 | if (state.explicit){ |
| 103 | System.out.print("> "); |
| 104 | state = state.nextState(sc.nextLine().trim(), state); |
| 105 | } else { |
| 106 | state = state.nextState(state.inputs.get(0), state); |
| 107 | } |
| 108 | } |
| 109 | sc.close(); |
| 110 | } |
| 111 | } |
| 112 | }}} |
| 113 | |
| 114 | Read more about implementing state machines in Java in these advanced tutorials [https://www.mirkosertic.de/blog/2013/04/implementing-state-machines-with-java-enums/ here] and [https://www.baeldung.com/java-enum-simple-state-machine here] |