// THIS PROGRAM WILL ONLY COMPILE WITH JDK 1.8 OR LATER ///////////////////////////////////////////////////////////////// // SAMPLE SUBCLASS OF FSM4: DFA to recognized regular expression a(a|b)*b // 4 states, state 2 is accept state, state 3 is 'dead state'. Should // set keeprunning to true and skipbadinput to false. import java.util.HashMap; public class dfa4 extends FSM4 // will cast chars to strings { String instring; // input string int ci; // current char position in instring HashMap Hash; // for implementing getindex public dfa4(String x) { instring = x; ci = 0; // current character in instring. numstates = 4; // state 0 is always start state maxinputs = 2; // input restricted to 'a', 'b' setTable(); } protected void setTable() { // set hash table mapping input to row index (for getindex) Hash = new HashMap(); Hash.put('a',0); Hash.put('b',1); // set action table (M declared in FSM4) M = new action[numstates][maxinputs]; int a = 0, b = 1; // for convenience M[0][a] = () -> 1; //M[0][a]=new action() { public int act() { return 1; } }; //before 1.8 M[0][b] = () -> { return 3; }; M[1][a] = () -> 1; // same as { return 1; } M[1][b] = () -> 2; M[2][a] = () -> 1; M[2][b] = () -> 2; for(int i=a;i<=b;i++) M[3][i] = () -> 3; // dead state }//setStateTable protected boolean acceptState(int s) { return s==2; } protected int getindex(Character x) { return Hash.get(x); } protected Character nextInput() // gets next available input, null if none { if (ci > instring.length()-1) return null; else return instring.charAt(ci++); } public static void main(String[] argv) { dfa4 automaton = new dfa4(argv[0]); // take command line input automaton.trace = true; // prints current input and state automaton.keeprunning = true; // process entire input automaton.skipbadinput = false; // terminates on invalid input boolean result = automaton.run(); System.out.println(result); } }//dfa4