Java array, NullPointerException?

孤街醉人 提交于 2019-12-17 06:56:19

问题


I declared two cards:

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

This works:

Hand hand1 = new Hand();

hand1.takeCard(card1);

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

Hand[] hand = new Hand[2];

hand[0].takeCard(card2);

回答1:


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.

Say

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



回答2:


I think you need to go though this... I will clear your concepts... Please refer Java tutorials as and when possible.. its helpful

http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html



来源:https://stackoverflow.com/questions/15170192/java-array-nullpointerexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!