How to convert NFA/DFA to java?

12,976

Solution 1

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
}

Solution 2

Take a look at dk.brics.automaton:

This Java package contains a DFA/NFA (finite-state automata) implementation with Unicode alphabet (UTF16) and support for the standard regular expression operations (concatenation, union, Kleene star) and a number of non-standard ones (intersection, complement, etc.)

Share:
12,976
Inco Mob
Author by

Inco Mob

I'm a mobile application development enthusiast. :)

Updated on June 14, 2022

Comments

  • Inco Mob
    Inco Mob about 2 years

    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.

  • M.K
    M.K over 11 years
    I have a question can such a DFA be modeled as a kind of a directed graph ? with links between nodes containing info about characters that produce a state transition kind of like the representation of DFAS on text books how will such and idea be implemented ?
  • ratchet freak
    ratchet freak over 11 years
    @M.K sure each node is a State object and each link is an entry in the transitions map