| 1 | 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: |
| 2 | {{{ |
| 3 | import java.util.*; |
| 4 | |
| 5 | public class StateMachine { |
| 6 | |
| 7 | private enum State { |
| 8 | // each state and its transitions (actions) |
| 9 | Ready(true, "Deposit", "Quit"), |
| 10 | Waiting(true, "Select", "Refund"), |
| 11 | Dispensing(true, "Remove"), |
| 12 | Refunding(false, "Refunding"), |
| 13 | Exiting(false, "Quiting"); |
| 14 | |
| 15 | State(boolean is_explicit, String... in) { |
| 16 | inputs = Arrays.asList(in); |
| 17 | explicit = is_explicit; |
| 18 | } |
| 19 | |
| 20 | State nextState(String input, State current) { |
| 21 | if (inputs.contains(input)) { |
| 22 | return map.getOrDefault(input, current); |
| 23 | } |
| 24 | return current; |
| 25 | } |
| 26 | |
| 27 | final List<String> inputs; |
| 28 | final static Map<String, State> map = new HashMap<>(); |
| 29 | final boolean explicit; |
| 30 | |
| 31 | // Map contains transitions, next state |
| 32 | static { |
| 33 | map.put("Deposit", State.Waiting); |
| 34 | map.put("Quit", State.Exiting); |
| 35 | map.put("Select", State.Dispensing); |
| 36 | map.put("Refund", State.Refunding); |
| 37 | map.put("Remove", State.Ready); |
| 38 | map.put("Refunding", State.Ready); |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | public static void main(String[] args) { |
| 43 | Scanner sc = new Scanner(System.in); |
| 44 | State state = State.Ready; |
| 45 | |
| 46 | while (state != State.Exiting) { |
| 47 | System.out.println(state.inputs); |
| 48 | if (state.explicit){ |
| 49 | System.out.print("> "); |
| 50 | state = state.nextState(sc.nextLine().trim(), state); |
| 51 | } else { |
| 52 | state = state.nextState(state.inputs.get(0), state); |
| 53 | } |
| 54 | } |
| 55 | sc.close(); |
| 56 | } |
| 57 | } |
| 58 | }}} |
| 59 | |
| 60 | 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] |