Java is object oriented so its natural to model a state as an object. Consider (and run) the following program (from here) that models a vending machine; it's a complex program that will take some time to understand; try running it in the debugger:
import java.util.*; public class StateMachine { private enum State { // each state and its transitions (actions) Ready(true, "Deposit", "Quit"), Waiting(true, "Select", "Refund"), Dispensing(true, "Remove"), Refunding(false, "Refunding"), Exiting(false, "Quiting"); State(boolean is_explicit, String... in) { inputs = Arrays.asList(in); explicit = is_explicit; } State nextState(String input, State current) { if (inputs.contains(input)) { return map.getOrDefault(input, current); } return current; } final List<String> inputs; final static Map<String, State> map = new HashMap<>(); final boolean explicit; // Map contains transitions, next state static { map.put("Deposit", State.Waiting); map.put("Quit", State.Exiting); map.put("Select", State.Dispensing); map.put("Refund", State.Refunding); map.put("Remove", State.Ready); map.put("Refunding", State.Ready); } } public static void main(String[] args) { Scanner sc = new Scanner(System.in); State state = State.Ready; while (state != State.Exiting) { System.out.println(state.inputs); if (state.explicit){ System.out.print("> "); state = state.nextState(sc.nextLine().trim(), state); } else { state = state.nextState(state.inputs.get(0), state); } } sc.close(); } }
Read more about implementing state machines in Java in these advanced tutorials here and here
Last modified 6 years ago
Last modified on Nov 6, 2019, 2:19:59 PM