Search code examples
javanullpointerexceptiondfa

NullPointerException for my States in my DFA?


I can't figure out why I am getting a NullPointerException in my code. I am trying to write simulator for a DFA and I have made my a Node type class that holds my states as seen below,

import java.util.Map;


class State{
        //fields
        Map<String,State> nextStates;

        public State passChar(String putIn){
            if(!nextStates.containsKey(putIn)){
                return null; 
            }
            return nextStates.get(putIn);
        }

        /**
         * Add a state that this state connects to.
         * @param sta the state that this state connects to when
         * a letter in the alphabet is passed to it.
         * @param pass the letter that is passed to it.
         */
        public void addNextState(String pass,State sta){
            nextStates.put(pass,sta);
        }
    }

I have tried I the main is in my driving class and is as such,

//Setting up my Q
        State q1 = new State();
        State q2 = new State();
        q1.addNextState("1", q1); //this is where my exception is thrown.
        q1.addNextState("0", q2);

Exception in thread "main" java.lang.NullPointerException
    at State.addNextState(State.java:25)
    at DFA.main(DFA.java:100)

Solution

  • You got to initialize the Map:

    Map<String,State> nextStates;
    

    Where are you doing it ? Something like this:

    Map<String,State> nextStates = new HasMap <>();
    

    That's the reason for NullPointerException.