Reputation: 327
I'm working on a method that is trying to display suit symbols of hands, so instead of 4C it would be 4(club), where (club) is the unicode of the club symbol.
For the switch statement, the HEART, CLUB, etc are declared as strings at the top of my program for the proper unicode.
My problem is that when I run the method the line containing "Card card = cards[i];" is producing a null pointer exception, and I have no idea why. Please help :)
I have "private Card[] cards;" at the top. When I try to do = hand.getCards it produces an error because ArrayList cannot be converted to Card[]
Here is my method right now.
private String displaySuits() {
for (int i = 0; i < hand.getCards().size(); i++) {
Card card = cards[i];
suits.append(" ");
suits.append(card.getRank());
switch (card.getSuit()) {
case SPADE:
suits.append(SPADE);
break;
case DIAMOND:
suits.append(DIAMOND);
break;
case CLUB:
suits.append(CLUB);
break;
case HEART:
suits.append(HEART);
break;
}
}
return suits.toString();
}
Upvotes: 1
Views: 11599
Reputation: 1835
You forgot to define the ArrayList of Card cards inside the method displaySuits.
private String displaySuits() {
ArrayList<Card> cards = hand.getCards();
StringBuilder suits = new StringBuilder();
for (int i = 0; i < cards.size(); i++) {
Card card = cards[i];
suits.append(" ");
suits.append(card.getRank());
switch (card.getSuit()) {
case SPADE:
suits.append((char)'\u2660');
break;
case DIAMOND:
suits.append((char)'\u2666');
break;
case CLUB:
suits.append((char)'\u2663');
break;
case HEART:
suits.append((char)'\u2764');
break;
}
}
return suits.toString();
}
Upvotes: 4
Reputation: 34166
As you are using an ArrayList
, don't declare cards
as an array Cards[]
, but as
private List<Card> cards;
initialize it in the class constructor (good programming practice)
cards = hand.getCards();
and you have to access elements like
cards.get(i);
Notes:
ArrayList
s are different from arrays.Don't forget to declare and initialize suits
, something like:
StringBuilder suits = new StringBuilder();
Upvotes: 1