1

So I am messing around trying to create a game. My main method calls another method that I have placed in the same file. It worked wonderfully when tested and for some reason it just stopped working and throws a NPE at me. As a preface, I am VERY green (only on chapter 5 of my Java textbook).

Here is the relevant parts of my code. I am passing info from my main method to another method which uses another method to do a calculation. This method is passed a reference to my gameboard object which contains a string. If I pass the pushCard method a constant instead of the getSlot** method, it works perfectly. Does the NPE mean that the newBoard object that I am referencing has become null? If I place a System.out.print right before windAction() is called, it prints the correct strings and not null. I am very confused.

Any help or advice will be a big help. Thanks in advance.

public static void main (String[] args)
{
    switch (playCard)
    {               
        case "wind":
        //slotselection has already been given a value
        windAction(slotSelection.toUpperCase()); 
        break;
        // There is more code here that is not shown...............
    }
}

public static void windAction(String slotSelection)
{
    switch (slotSelection.toUpperCase())
    {
        case "A1":
        {
            if (pushCard(newBoard.getSlotA2(), newBoard.getSlotA3()) == true)
                newBoard.setSlotA3(newBoard.getSlotA2());
                newBoard.setSlotA2("EMPTY");

            if (pushCard(newBoard.getSlotB1, newBoard.getSlotC1) == true)
                newBoard.setSlotC1(newBoard.getSlotB1());
                newBoard.setSlotB1("EMPTY");

        } //end case A1
        break;

        // There is more code here that is not shown...............
    }
}




public static Boolean pushCard(String S1, String S2)

{
    Boolean result = null; 

    if ((S1 == "fire") | (S1 == "water") | (S1 == "wind")){
        if ((S2 != "fire") | (S2 != "water") | (S2 != "wind"))
            result = true;
        else
            result = false;
    }

    return result;

}//end push card method
Edward Falk
  • 9,991
  • 11
  • 77
  • 112
Sev
  • 883
  • 1
  • 14
  • 34

1 Answers1

2

I believe that the NullPointerException may rise from your pushCard method -> You are using the Boolean class instead of the boolean primitive, and have a case in which it may be null.

You are using a bit-wise or operation to check for a logical or and you are checking String equality using ==, this will cause the if statement to fail and thus result will not be set:

Boolean result = null; 

if ((S1 == "fire") | (S1 == "water") | (S1 == "wind")){
    ...
}

should be:

boolean result = false; 

if ("fire".equals(S1) || "water".equals(S1) || "wind".equals(S1)){
    ...
}

Similar changes must be made for the if statement inside this one.

Sinkingpoint
  • 7,449
  • 2
  • 29
  • 45