/* counter automaton that accepts matching ()'s like ((()()) 3 states: 0 is both start and accept state, state 2 is dead state. In state 0, on seeing (, sets counter to 1 and transition to state 1, else goto state 2. State 1 increments counter on seeing (, decrements on seeing ), making sure that counter doesn't become negative by transitioning back to 0 when counter is 1. This machine should run with keeprunning and skipbadinput both set to true */ public class parensfsm extends FSM4 { protected String instring; // input string protected int indx=0; // indexes instring protected int cx = 0; // counter for automaton java.util.HashMap Hash; // for implementing getindex public parensfsm(String x) { instring = x; numstates = 3; maxinputs = 2; cx = 0; setTable(); } protected Character nextInput() { if (indx(); Hash.put('(',0); Hash.put(')',1); // set transition table M = new action[numstates][maxinputs]; M[0][0] = () -> { cx=1; return 1; }; M[0][1] = () -> 2; // 2 is dead state M[1][0] = () -> { cx++; return 1; }; M[1][1] = () -> { // seen ')' cx--; if (cx==0) return 0; else return 1; }; M[2][0] = M[2][1] = () -> 2; // not needed with skipbadinput=true }//setStateTable public static void main(String[] av) { String x = av[0]; // command-line string parensfsm machine = new parensfsm(x); machine.trace = true; machine.keeprunning = true; // process entire input boolean r = machine.run(); System.out.println(r); } } // run: java parensfsm "(()))" (should reject)