2013-08-01 37 views
1

因此,我正在嘗試創建一個遊戲。我的主要方法調用了我放在同一個文件中的另一種方法。它在測試時運行得非常好,由於某種原因它停止工作並向我拋出NPE。作爲前言,我非常綠色(僅在我的Java教科書第5章中)。Nullpointerexception在與主要方法相同的文件中調用一個方法時

這是我的代碼的相關部分。我從我的主要方法傳遞信息到使用另一種方法進行計算的另一種方法。該方法傳遞給我的包含字符串的遊戲板對象的引用。如果我將pushCard方法傳遞給常量而不是getSlot **方法,那麼它可以很好地工作。 NPE是否意味着我所引用的newBoard對象已變爲null?如果我在調用windAction()之前放置一個System.out.print,它將打印正確的字符串,而不是null。我很困擾。

任何幫助或建議將是一個很大的幫助。提前致謝。

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 
+1

哪一行產生空指針異常> – tbodt

+4

您可以添加堆棧跟蹤嗎? – Smit

+2

newBoard在哪裏定義? –

回答

2

我相信NullPointerException異常可能與您pushCard方法上漲 - >您正在使用Boolean類而不是基本布爾,並在它可能爲空的情況。

您使用的是逐位或操作檢查的邏輯或和你正在檢查使用==字符串相等,這將導致if語句失敗,從而導致不會設置:

Boolean result = null; 

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

應該是:

boolean result = false; 

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

類似的變化必須爲這一個內部的if語句進行。

+3

等一下,你怎麼知道這是OP的源頭的一部分? o.O –

+2

在源代碼中聲明的最後一個方法? '公共靜態布爾pushCard(字符串S1,字符串S2)' – Sinkingpoint

+0

這樣做!感謝您快速準確的回覆。你搖滾。 – Sevren

相關問題