Foobar
Foobar

Reputation: 8467

How to access a array in a instance

I am making a card game and I have the following section of code (a small excerpt):


Hand[] hands;

hands = new Hand[t];

for (i = 1; i > t; i++) {
    hands[i] = new Hand();
}

public class Hand {

    Hand() {
        Card[] hand;

        hand = new Card[52];
    }
}

How would I access the array in the Hand object?

For example, let's say I had a instance of the Hand class called hand1, how would I access the array hand in the hand1 object?

Doing hand1.hand[x] did not work.

Upvotes: 0

Views: 68

Answers (3)

Eran
Eran

Reputation: 393821

You should define a getter and a setter :

public Card getCard (int i)
    throws SomeException()
{
    if (i < 0 || i >= hand.length)
        throw new SomeException();
    return hand[i];
}

public void setCard (Card theCard, int i)
    throws SomeException()
{
    if (i < 0 || i >= hand.length)
        throw new SomeException();
    hand[i] = theCard;
}

Of course, you should add range checks for i.

In addition, as Mik correctly commented, define the hand in the correct place (outside the constructor) :

public class Hand {
    private Card[] hand;
    Hand() {
        hand = new Card[52];
    }
}

Upvotes: 2

Juxhin
Juxhin

Reputation: 5600

  Hand() {
    Card[] hand;

    hand = new Card[52];
}

Card[] hand is a local variable as you're declaring it inside the Hand() constructor. If you want to use this variable then you should declare it globally like so:

private Card[] hand;
  Hand() {
    hand = new Card[52];
}

And have getter & setter methods to retrieve that private variable (this is called 'encapsulation'). I don't think there's any need to get into those

Upvotes: 1

Mik378
Mik378

Reputation: 22171

Doing hand1.hand[x] did not work.

You are declaring your "field" in the constructor.

You have to declare it outside otherwise it would simply be a local variable.

public class Hand {
     Card[] hand;

     Hand() {
       hand = new Card[52];
    }
}

However, I presume you know encapsulation so I don't start this subject.

Upvotes: 2

Related Questions