初始化对象数组仍然获得空指针异常?

时间:2013-04-04 03:14:37

标签: java arrays nullpointerexception syntax-error poker

我是编程新手,我正在尝试用Java创建一个扑克计划。

这段代码在Player类中,我正在尝试构造一个空手。无论我如何填充数组(使用循环,像这样等),Eclipse告诉我当我尝试在手[1]或手[i]或其他任何东西上调用方法时,我有一个空指针。

通常,没有任何编译时错误。但是当我单独构建手中的每张卡片时 - 见下文 - 编译器会感到不安......

以下播放器和类的相关片段。

我做错了什么?我搜索了很多但仍然不明白 提前谢谢!

class Player {

// Sets up a blank card array called "hand"
// with five (0,0) slots for real cards.
private Card[] hand = new Card[5];

private Card hand[0] = new Card(0, 0);  // error: syntax error on token "0", delete this token
private Card hand[1] = new Card(0, 0);  // error: syntax error on token "1", delete this token
private Card hand[2] = new Card(0, 0);  // error: syntax error on token "2", delete this token
private Card hand[3] = new Card(0, 0);  // error: syntax error on token "3", delete this token
private Card hand[4] = new Card(0, 0);  // error: syntax error on token "4", delete this token

class Card {
// Sets the default suit/number to zero.
// Lucky for me, such a 0-0 Card does not exist.
private int number = 0;
private int suit = 0;

// Constructs the Card itself by giving it a number and suit.
// Numbers/suits can *only* be set here.

public Card(int n, int s) {

    // Bound tester for suit/number values.
    // Number has to be between 1 and 14 inclusive (Ace low-Ace high).
    // Suit has to be between 1 and 4 inclusive (H/C/D/S).
    if (n > 0 && n <= 14 && s > 0 && s <= 4) {
        number = n;
        suit = s;
    }

2 个答案:

答案 0 :(得分:4)

您正在将变量声明与数组初始化混合,从而导致语法错误的代码。您已经声明了要用作存储的数组,要初始化它,您可以使用块:

private Card[] hand = new Card[5];

{
    hand[0] = new Card(0, 0); 
    hand[1] = new Card(0, 0);
    hand[2] = new Card(0, 0);
    hand[3] = new Card(0, 0);
    hand[4] = new Card(0, 0);
}

您也可以在一行中声明并初始化数组:

private Card[] hand = new Card[] {
    new Card(0, 0),
    new Card(0, 0),
    new Card(0, 0),
    new Card(0, 0),
    new Card(0, 0),
};

答案 1 :(得分:0)

错误的原因是该行

private Card hand[0] = new Card(0, 0);

看起来像是Java的声明,你只能声明一个简单的标识符。