Java 简单二十一点游戏,java.lang.NullPointerException
我正在编写一个java程序来制作一个简单的二十一点游戏。
我正在使用一系列卡片对象作为用户的手。
用户将收到两张牌,但他们可以要求再拿一张牌,直到达到 5 张牌的限制。
出于这个原因,我制作了具有 5 个插槽的卡牌对象数组,以便可以将更多卡牌添加到手牌中。
但是,现在我无法在发牌时打印原始手牌,或者如果用户不要求提供完整的 5 张牌,因为我的数组将包含 null
对象。
解决这个问题最快、最简单、最简单的方法是什么?
I am writing a java program to make a simple blackjack game.
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.
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.
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.
What is the quickest, simplest and easiest way to fix this issue?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
将用于打印卡片值的行放置在 if 语句中,以检查数组值是否为空。像这样的东西:
Place the line to print the value of the card inside an if statement that checks to see whether the array value is null. Something like:
不要使用数组 - 使用列表,也许是 ArrayList。
然后,您可以简单地说:
我假设您的 Card 类有一个 toString() 方法,并且“hand”是一个 List
Don't use an array - use a List, perhaps an ArrayList.
Then, you can simply say:
Where I'm assuming your Card class has a toString() method, and 'hand' is a List<Card>
如您所知,您无法访问空对象内部的任何内容。在这种情况下,您应该在打印时检查这 5 张卡中的每一张是否为空。
You cannot, as you know, access anything inside of a null object. In this case, you should check each of the 5 cards if it is null when printing.
在做任何事情之前检查 null:
这些方法显然是假的,但尝试类似的方法。
但正如上面的评论所说,你最好有一个列表。
Check for null before you do anything:
The methods are fake obviously but try something like that.
But as the comment above says, you would be better off with a list.