本文介绍了Java 数组,NullPointerException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我宣布了两张牌:

Card card1 = new Card('3', Card.Suit.clubs);
Card card2 = new Card('T', Card.Suit.diamonds);

这有效:

Hand hand1 = new Hand();

hand1.takeCard(card1);

但是为什么这不起作用?它在第二行给了我一个 NullPointerException:

But why does this not work? It gives me a NullPointerException on second line:

Hand[] hand = new Hand[2];

hand[0].takeCard(card2);

推荐答案

您正在声明一个由 2 手牌组成的数组.这只是设置阵列.然后,您需要实例化数组内的手对象.

You are declaring an array of 2 hands. This is just setting up the array. You then need to instantiate the hand objects inside the array.

hand[0] = new Hand();
hand[1] = new Hand();

这篇关于Java 数组,NullPointerException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 19:08