2011-05-05 78 views
0

美好的一天!如何訪問對象實例的數組索引

我想知道如何訪問對象實例的數組索引。

我的代碼如下:

public class PokerPlayer { 

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

    //getter and setter 
} 

我想要的就是訪問cardsOnHandArray [指數],這樣我可以把它叫做另一個類,並設置每個索引值...

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 i and store something on it... 
      } 
     } 
    } 
} 

任何意見將不勝感激。我怎樣才能改善我的OO設計?預先感謝您

+0

你應該真的避免幻數,也許擺脫'我<5',並從卡陣列中獲得值,即'我 toc777 2011-05-05 15:56:21

回答

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

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

然後使用:

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

您幾乎擁有它。只要你內心的循環中調用此:

cardsOnHand[i] = new Card(); 

當然,改變根據您的要求是什麼被分配到陣列中。

+0

但我想存儲的東西在數組cardsOnHand [5] – newbie 2011-05-05 15:46:35

+1

沒有'cardOnHand [5]'這樣的事情,如果數組的長度是5.索引值將是0,1,2,3,4 。 – Jeremy 2011-05-05 15:47:40

1

你可以做:

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

這應該工作:

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

}

1

由於你的cardsOnHand數組是私有的,你必須使用你的(未提供的)setter函數。 這可能是像

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

,並在你的循環使用
player.setCard(i, something)

1

假設你PokerPlayer先後爲cardsOnHand陣列吸氣:

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

不過,我覺得更好的解決方案是添加一個方法

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

到您的PokerPlayer