Search code examples
javafinite-automataautomatastate-machine

How to convert NFA/DFA to java?


I have a scenario where I have designed the NFA and using JFLAP I have converted it to DFA.

I need to know, how to code it in Java?

Basically how to implement those state transitions in Java. I have seen some examples which do this using switch and if statements, but I can't see any relation to DFA/NFA design and how to use it to implement in Java.


Solution

  • if you want to use a more object oriented design over while(true)switch(state){...}

    public class State{
        private Map<Character,State> transitions=new HashMap<Character,State>();
    
        public void addTransition(char ch,State st){
            transitions.put(ch,st);
        }
    
        public State next(char ch){
            return transitions.get(ch);
        }
    
        private boolean fin=false;
        public boolean isFinal(){return fin;}
        public boolean setFinal(boolean f){fin=f;}        
    
    
    }
    

    and then the loop will be

    State currState=startState;
    while(currState!=null && input.hasNextChar()){//you can also end directly when final state is reached
        char next = input.nextChar();//get next character
        currState = currState.next(next);
    }
    
    if(currState!=null && currState.isFinal()){
        // reached final state
    }else{
        // to bad didn't match
    }