开发者

How to access an array index of an Object instance

Good day!

I am wondering How can I access an array index of an Object instance.

My code is as follows:

public class PokerPlayer {

    private String name = null;
    private Card [] cardsOnHand = new Card[5]; 

    //getter and setter
}

What i want is to access the cardsOnHandArray[index] so that i can call it on another class and set the values per index...

public class PokerGame {
      public static void main (String [] Args){
      PokerPlayer players []= new PokerPlayer[4];
      for(PokerPlayer player : players){
          for(int i =0; i<5; i++){
            //ACCESS cardsOnHand index 开发者_StackOverflow中文版i and store something on it...
          }
        }
    }
}

Any advice would be highly appreciated. How can i also improve my OO design? Thank you in advance


public class PokerPlayer {
...
public Card getCard(int index) {
  return this.cardsOnHand[index];
}

public void setCard(int index, Card card) {
  this.cardsOnHand[index] = card;
}
...
}

then use:

player.getCard(i);
player.setCard(i,new Card());


You almost have it. Just call this inside your inner loop:

cardsOnHand[i] = new Card();

Of course, change what is being assigned to the array according to your requirements.


you can do as:

for(PokerPlayer player : players){
          for(int i =0; i<5; i++){
            Card[] cards= player[i].getCardsOnHand();
            cards[i] = new Card();
          }
        }


This should work:

public class PokerGame {
  public static void main (String [] Args){
  PokerPlayer players []= new PokerPlayer[4];
  for(PokerPlayer player : players){
      for(int i =0; i<5; i++){
        Card card = player.cardsOnHand[i];
      }
    }
}

}


Since your cardsOnHand array is private, you have to use your (unprovided) setter function. Which could be something like

public void setCard(int index, Card value){
   cardsOnHand[index] = value;
}

And in used in your loop as
player.setCard(i, something)


Assuming that your PokerPlayer has a getter for the cardsOnHand array:

public class PokerGame {
      public static void main (String [] Args){
      PokerPlayer players []= new PokerPlayer[4];
      for(PokerPlayer player : players){
          for(int i =0; i<5; i++){
                player.getCardsOnHand()[i] = new Card();
          }
        }
    }
}

However, I think that a better solution is to add a method

public void setCard(Card card, int index) {
    assert index < 5;
    cardOnHands[index] = card
}

to your PokerPlayer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜