2011-05-01 71 views
1
import java.util.ArrayList; 
import java.util.Collections; 

public class Cards 
{ 
    public static enum cards 
    { 
     D_A, D_2, D_3, D_4, D_5, D_6, D_7, D_8, D_9, D_10, D_J, D_Q, D_K, 
     H_A, H_2, H_3, H_4, H_5, H_6, H_7, H_8, H_9, H_10, H_J, H_Q, H_K, 
     C_A, C_2, C_3, C_4, C_5, C_6, C_7, C_8, C_9, C_10, C_J, C_Q, C_K, 
     S_A, S_2, S_3, S_4, S_5, S_6, S_7, S_8, S_9, S_10, S_J, S_Q, S_K, 
    } 

    public Cards() 
    { 
     ArrayList<cards> deck; 
     deck = new ArrayList<cards>(51); 
     for (cards card : cards.values()) 
     { 
      deck.add(card); 
     } 
     Collections.shuffle(deck); 
     String img = deck.get(2).toString()+".gif";  
     System.out.println(img); 
    } 

    public static void main(String[] args) 
    { 
     Cards CardDeck = new Cards(); 
    } 
} 

我想訪問不同類中的數組列表。我怎樣才能做到這一點?如何從Java中的其他類訪問數組列表?

回答

1

要訪問ArrayList,需要將該列表作爲類的成員。 然後,您需要建立一個訪問器方法,或者將該成員變量設爲public(不推薦)。

第一個解決方案在這裏提供:

public class Cards 
{ 
    private ArrayList<cards> deck; 

    public static enum cards 
    { 
     D_A, D_2, D_3, D_4, D_5, D_6, D_7, D_8, D_9, D_10, D_J, D_Q, D_K, 
     H_A, H_2, H_3, H_4, H_5, H_6, H_7, H_8, H_9, H_10, H_J, H_Q, H_K, 
     C_A, C_2, C_3, C_4, C_5, C_6, C_7, C_8, C_9, C_10, C_J, C_Q, C_K, 
     S_A, S_2, S_3, S_4, S_5, S_6, S_7, S_8, S_9, S_10, S_J, S_Q, S_K, 
    } 

    public Cards() 
    { 
     deck = new ArrayList<cards>(51); 
     for (cards card : cards.values()) 
     { 
      deck.add(card); 
     } 
     Collections.shuffle(deck); 
     String img = deck.get(2).toString()+".gif";  
     System.out.println(img); 
    } 
    public ArrayList <cards> getDeck() { 
     return deck; 
    } 
    public static void main(String[] args) 
    { 
     Cards CardDeck = new Cards(); 
    } 
} 
4

使用Cards.cards.D_A或無論你想要什麼。如果它們不在同一個包中,請不要忘記導入課程...

+0

+1先用最好的。我每次都會收到人工驗證*我今天回答,這只是不公平。 – 2011-05-01 02:04:13

+0

所以如果我只是想整個列表youd把Cards.cards? – gheystyle 2011-05-01 02:13:22

+2

這將如何聲明此枚舉類型的變量 - Cards.cards myCard = Cards.cards.D_A。在這裏看到更多:http://download.oracle.com/javase/1.5.0/docs/guide/language/enums.html – MByD 2011-05-01 02:16:40

3

由於它是靜態的,Cards.cards應該可以工作。

+0

幾個小時前我得到了10次...所以我知道你的感受+1 :) – MByD 2011-05-01 02:06:20

+0

+1 @jcomeau_ictx – Boro 2011-05-01 02:26:56