I'm making a program that takes in an input of lets say: 3H 4C 8S 2D 4H
a poker hand with a three of hearts, four of clubs etc.
I have a card class and each card has a rank and suit which are both defined as enums. These are the methods I use in the Card class:
// METHOD TO GET CARDS IN RANK ORDER
public static Card[] getHand(String[] args){
Card[] hand = new Card[5];
for (Rank r : Rank.values()) {
int j=0;
for (int i = 0 ; i < args.length ; i++) {
if(r.rankNum().equals(args[i].substring(0,1))){
hand[j] = new Card(r, Card.getSuit(args, i));
j++;
}
}
} return hand;
}
// METHOD TO GET SUIT
public static Suit getSuit(String[] args, int i) {
for (Suit s : Suit.values()) {
if (s.suitCode().equals(args[i].substring(1,2))) {
return s;
}
} return null;
}
In the main I do the following:
// TEST CARD ARRAY AND CARD PRINT
Card[] handTest = new Card[5];
handTest[0] = new Card(Rank.TWO, Suit.CLUBS);
handTest[1] = new Card(Rank.TWO, Suit.CLUBS);
handTest[2] = new Card(Rank.TWO, Suit.CLUBS);
handTest[3] = new Card(Rank.TWO, Suit.CLUBS);
handTest[4] = new Card(Rank.TWO, Suit.CLUBS);
for (int i = 0 ; i < 5 ; i++){
handTest[i].printCard();
}
// TRY WITH ACTUAL ARGUMENT INPUT (3H 4D 7C 2D 8S)
Card[] hand = new Card[5];
hand = Card.getHand(args);
for (int i = 0 ; i < 5 ; i++){
hand[i].printCard();
}
I get the following output
Suit: CLUBS Rank: TWO
Suit: CLUBS Rank: TWO
Suit: CLUBS Rank: TWO
Suit: CLUBS Rank: TWO
Suit: CLUBS Rank: TWO
Suit: SPADES Rank: EIGHT
Exception in thread "main" java.lang.NullPointerException
at Poker.main(Poker.java:20)
If I have the printCard
method within the innermost loop of getHand
, I don't get errors but its after the getHand
method has run that I get the null pointer exception.
I have now read some posts explaining null pointer exceptions but I cannot seem to fix this. Line 20 refers to hand[i].printCard();