0

I'm completely new to programming and am trying to create a Poker program in Java.

This bit of code is in the Player class, where I'm trying to construct an empty hand. No matter how I fill the array (with a loop, like this, etc.), Eclipse tells me I have a null pointer when I try to call a method on hand[1] or hand[ i ] or whatever.

Usually, there aren't any compile-time errors. But when I construct each card in the hand individually––see below––the compiler gets upset...

Relevant fragments of Player and Class below.

What am I doing wrong? I've searched quite a bit and still don't understand.
Thank you in advance!

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 Answers2

4

You are mixing variable declaration with array initialization, resulting in syntactically incorrect code. You've already declared the array you want to use as storage, to initialize it you can use a block:

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

You could also declare and initialize the array all on one line:

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),
};
Perception
  • 79,279
  • 19
  • 185
  • 195
  • Thanks, this [tutorial](http://docs.oracle.com/javase/tutorial/java/javaOO/initial.html) covers initialization blocks for those who are interested. – Sotirios Delimanolis Apr 04 '13 at 03:23
0

The reason for the error is that the line

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

looks like a declaration to Java, and you can only declare a simple identifier.

Ray Toal
  • 86,166
  • 18
  • 182
  • 232