简体   繁体   English

Java简单BlackJack游戏,java.lang.NullPointerException

[英]Java Simple BlackJack Game, java.lang.NullPointerException

I am writing a java program to make a simple blackjack game. 我正在编写一个Java程序来制作一个简单的二十一点游戏。

I am using an array of card objects as the users hand. 我正在使用一系列卡对象作为用户手。

the user will be dealt two cards in their hand, however they can ask for another card until they reach a limit of 5 cards. 该用户手中将获得两张卡,但是他们可以要求另一张卡,直到达到5张卡的限额为止。

For this reason I have made the array of card objects with 5 slots to allow for the possibility of further cards being added to the hand. 因此,我制作了具有5个插槽的纸牌对象阵列,以允许将更多的纸牌添加到手上。

However now I can't print the original hand when dealt or if the user does not ask for the full 5 cards because my array will have null objects. 但是现在我不能在发牌时打印原始的手牌,或者用户不要求完整的5张牌,因为我的数组将包含null对象。

What is the quickest, simplest and easiest way to fix this issue? 解决此问题的最快,最简单和最简单的方法是什么?

Place the line to print the value of the card inside an if statement that checks to see whether the array value is null. 将行放置在卡的if语句中打印卡的值,该语句检查以查看数组值是否为空。 Something like: 就像是:

for(int i = 0; i < cardArray.length ; i++)
{
  if(cardArray[i] != null)
      System.out.print(cardArray.value);
}

Don't use an array - use a List, perhaps an ArrayList. 不要使用数组-使用列表,也许是ArrayList。

Then, you can simply say: 然后,您可以简单地说:

for (Card card : hand) {
  System.out.println(card);
}

Where I'm assuming your Card class has a toString() method, and 'hand' is a List<Card> 我假设您的Card类具有toString()方法,而“ hand”是List <Card>

You cannot, as you know, access anything inside of a null object. 如您所知,您不能访问null对象内部的任何内容。 In this case, you should check each of the 5 cards if it is null when printing. 在这种情况下,打印时应检查5张卡中的每张是否为空。

Check for null before you do anything: 在执行任何操作之前,请检查null:

if(x[i] == null){
    don't.do.anything();
}else {
    print.something();
}

The methods are fake obviously but try something like that. 这些方法显然是伪造的,但可以尝试类似的方法。

But as the comment above says, you would be better off with a list. 但是,正如上面的评论所述,您最好使用列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM