2016-11-21 61 views
-1

我得到這個空指針異常,我不知道爲什麼java的撲克遊戲空指針

public static boolean hasPair(Card[] cards) { 
    int k=0; 
    cards = new Card[5]; 

    for (int atPos = 0; atPos<5; atPos++){ 
     for (int atPos2 = atPos+1; atPos2<5; atPos2++){ 

      if(cards[atPos].getValue() == cards[atPos2].getValue()){ 
       k++; 
      } 
      if (atPos2 == (cards.length-1) && k!=1){ 
       k=0; 
      } 
      else if (atPos2 == (cards.length-1) && k>=2){ 
       return true; 
      } 
     } 
    } 
    return false; 
} 

我的方法是測試我的手牌是否有持有相同值的兩張牌和nul指針說這是在這一行

if(cards[atPos].getValue() == cards[atPos2].getValue()){ 

我也有這種方法...我可以使用它作爲助手嗎?

public Card[] deal(int numCards) { 
    Card[] newArray; 
    newArray = new Card[numCards]; 
     for (int index=0; index<numCards; index++){ 
      newArray[index] = cards.get(0); 
      cards.remove(0); 
    } 
    return newArray; 
    } 
+0

既然你行'卡=新卡[5];'你的方法的頂部,你的'cards'陣列將永遠是空的。可能不是你想要的,因爲你正在向該方法傳遞一個數組。 – khelwood

+0

我該如何解決這個問題? – masonft

回答

3

在第二行中創建一個新的物體卡片陣列。該數組中的每個對象都是空的,所以您需要先填充數組。

+0

我該怎麼做? – masonft

+0

您可以迭代陣列並將對象卡添加到每個位置。 是這樣的:對於 – klancar16

+0

(INT I = 0; I klancar16