javaarrayspokermutators

How do you write an advanced mutator method for arrays?


I'm relatively new to programming, so this is very confusing to me. In this program, I declared and instantiated an array of 5 card EMPTY SLOTS (from a program called Card.java in which all the cards are complete). This is my constructor method:

 public BasicPlayer()
 {
    myHand = new Card[5];
 }

Then I'm supposed to declare an advanced mutator and accessor method for arrays (the getter and setter I assume), which is where I am stuck. For the accessor method, I am supposed to get a card from the players hand:

   public Card getCard()
   {
     card tempCard = myHand [numberDealt];
     numberDealt ++;
     return tempCard;
   }

but then for the mutator method, I am supposed to set a SINGULAR CARD into the player's hand (I will create a loop in a different class setting more cards into the hand, but for now, I just need one). This is where I am stuck. What am I supposed to do?


Solution

  • It could be something as simple as this.

       // setters typically don't return anything.
       // and idx must satisfy 0 <= idx < myHand.length
       public void setCard(int idx, Card card) {
         myHand[idx] = card;
       }
    

    However, I noticed in your other method

       public Card getCard() {
         Card tempCard = myHand [numberDealt];
         numberDealt ++;
         return tempCard;
       }
    

    Be careful with the numberDealt increment. If it goes beyond 4 you will throw an indexed based Exception for exceeding the array size. How you handle this is up to you.