Click!
Here is the complete program. If you want to run it, highlight the entire program with the mouse, copy it to the clipboard (control-C), then paste it into your usual Java editor (control-V). Save to a file (from the editor) and compile and run as usual.
class FSAaz { public boolean recognize(String str) { final int reject = 3; // rejection state int state = 0; // the current state char current; // the current character int index = 0 ; // index of the current character // continue while there are input characters // and the reject state has not been reached while ( index < str.length() && state != reject ) { current = str.charAt( index++ ) ; // State 0 if ( state==0 && current=='a' ) state = 1; // State 1 else if ( state==1 && current >= 'a' && current <= 'y') state = 1; else if ( state==1 && current == 'z') state = 2; // State 2 else if ( state==2 && current >= 'a' && current <= 'y') state = 1; else if ( state==2 && current == 'z') state = 2; // no transition else state = reject ; } // if the final state was reached with the last character, // the string is accepted. if ( index == str.length() && state == 2 ) return true; else return false; } } class FSAtester { public static void main (String[] args) { String str = null; FSAaz fsa = new FSAaz(); str = args[0]; if ( fsa.recognize( str ) ) System.out.println("The string is recognized."); else System.out.println("The string is rejected."); } }
Here is a run of the program. Of course, you should compile and run your own version:
C:\CAI\FiniteAutomata\Section02>javac FSAtester.java C:\CAI\FiniteAutomata\Section02>java FSAtester annnz The string is recognized. C:\CAI\FiniteAutomata\Section02>java FSAtester annnz The string is recognized. C:\CAI\FiniteAutomata\Section02>java FSAtester ratz The string is rejected.
Can this program be used as a prototype for other finite state automata?