0

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)
Nate
  • 65
  • 7
  • You never initialized `nextStates`, so it's null. When you try to access its `.put` method, NPE. – yshavit Jun 09 '17 at 03:43
  • The problem in this line of code: nextStates.put(pass,sta); Because nextStates is not initialized yet. You should add `new HashMap();` to be like that: Map nextStates = new HashMap(); – Fady Saad Jun 09 '17 at 03:44

1 Answers1

0

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.

Uday
  • 1,165
  • 9
  • 12