我正在制作一个程序,输入一个让我们说:3H 4C 8S 2D 4H
一个拥有三颗心,四个俱乐部等的扑克牌。
我有一个卡片类,每张卡片都有等级和套装,都被定义为枚举。这些是我在Card类中使用的方法:
// 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;
}
在主要内容中,我执行以下操作:
// 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();
}
我得到以下输出
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)
如果我在printCard
的最内层循环中有getHand
方法,我不会得到错误,但是在getHand
方法运行之后我得到空指针异常。
我现在已经阅读了一些解释空指针异常的帖子,但我似乎无法解决这个问题。第20行引用hand[i].printCard();