Pinky King
Pinky King

Reputation: 1

Null Pointer Exception with if statement with Array

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;        
}

Upvotes: 0

Views: 171

Answers (2)

Reimeus
Reimeus

Reputation: 159784

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

boolean [] currentGuessArray = new boolean[20];

with

currentGuessArray = new boolean[20];

Upvotes: 4

Reisclef
Reisclef

Reputation: 2148

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);
}

Upvotes: 0

Related Questions