-1

I'm getting a null pointer exception for this and I'm not sure why

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

My method is testing whether or not my hand of cards has two cards that hold the same value and the nul pointer says it's within this line

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

I also have this method...could i use it as a helper?

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;
    }
masonft
  • 9
  • 5
  • Since you have the line `cards = new Card[5];` at the top of your method, your `cards` array will always be empty. Probably not what you intended, since you are passing an array into the method. – khelwood Nov 21 '16 at 12:59
  • how would I fix that? – masonft Nov 21 '16 at 13:01

1 Answers1

3

In second line you create a new array of objects Card. Every object in that array is null, so you need to fill the array first.

klancar16
  • 89
  • 4