0

我对编程完全陌生,正在尝试用 Java 创建一个扑克程序。

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

通常,没有任何编译时错误。但是当我单独构造手中的每张牌时——见下文——编译器会感到不安……

下面是 Player 和 Class 的相关片段。

我究竟做错了什么?我已经搜索了很多,但仍然不明白。
先感谢您!

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;
    }
4

2 回答 2

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),
};
于 2013-04-04T03:19:01.563 回答
0

错误的原因是该行

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

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

于 2013-04-04T03:17:43.997 回答