0

I keep getting a null pointer exception at the line surrounded by stars. How can I fix this? I don't understand why it's happening because I filled currentGuessArray with false. (I didn't include all of my code, just the parts that have to do with currentGuessArray.)

public static boolean [] currentGuessArray;


public void initGuess() { 
   // creates a new Array for the currentGuessArray variable 
   boolean [] currentGuessArray = new boolean[20];
   // initialize all slots to false
   Arrays.fill(currentGuessArray, false);
}

public String getCurrentGuessArray() { 
   // the returned String has "_ " for unrevealed letters
   // “walk over” the currentWord and currentGuessArray Arrays and create the String
   if ( !currentWord.equals("Shrek") && !currentWord.equals("Dobby") ) {
       int j = 1;
       while ( (!currentWord.substring(j, j).equals(" ")) && (j < currentWord.length()) ) {
          j++;
          spaceSpot = j;
       }
   }
   int k = 0;
   String displayString = "";
   while ( k < currentWord.length() ) {
      if ( k == spaceSpot ) {
         displayString = displayString + "   ";
      }
      **else if ( currentGuessArray[k] == true ) {**
         displayString = displayString + currentWord.substring(k, k);
      }
      else {
         displayString = displayString + "_ ";
      }
      k++;
   }
   return displayString;        
}
1
  • Any specific reason why currentGuessArray array is static? Commented Jun 20, 2015 at 13:33

2 Answers 2

4

Assuming initGuess is being called, you're shadowing currentGuessArray. Replace

boolean [] currentGuessArray = new boolean[20];

with

currentGuessArray = new boolean[20];
Sign up to request clarification or add additional context in comments.

Comments

0

You've defined a local variable with the same name as the class variable.

Therefore, the local variable is being declared, filled with false, and then it's garbage collected at the end of the method.

When you're referencing currentGuessArray (as a class variable I suppose somewhere in client code), it has never been set to a reference of anything, therefore you get the null pointer exception. Try the below:

public static boolean [] currentGuessArray;


public void initGuess() { 
   // creates a new Array for the currentGuessArray variable 
   currentGuessArray = new boolean[20];                       //Reisclef changed this line
   // initialize all slots to false
   Arrays.fill(currentGuessArray, false);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.