2017-04-24 35 views
1

我想創建一個構造函數來創建一個數組並用自定義對象填充該數組。這個數組將代表一副牌。Java:我如何製作一個數組並在構造函數中用對象填充它?

public class DeckOfCards { 
public static Card[] deck = new Card[52]; 

//constructor 
DeckOfCards(){ 
    Card[] deck = new Card[52]; 

    deck[0]=new Card("Ace","Clubs"); deck[1]=new Card("Two","Clubs"); 
    deck[2]=new Card("Three","Clubs");..(ect)...deck[49]=new 
    Card("Jack","Diamonds"); 
    deck[50]=new Card("Queen","Diamonds"); deck[51]=new Card("King","Diamonds"); 
} 

我覺得這應該構造函數創建一個數組,並與卡對象填充它,但它不承認從DeckOfCards()作爲數組實例化的任何對象。

回答

1

您有一個範圍的問題,因爲你是在構造函數中再次

Card[] deck = new Card[52]; 

宣佈,留下不影響全球的成員,請改用甲板對象....(順便說一下,沒有必要靜態對象...)

DeckOfCards(){ 

    deck[0]=new Card("Ace","Clubs"); deck[1]=new Card("Two","Clubs"); 
    deck[2]=new Card("Three","Clubs");..(ect.).deck[49]=new 
    Card("Jack","Diamonds"); 
    deck[50]=new Card("Queen","Diamonds"); deck[51]=new Card("King","Diamonds"); 
} 
+0

我該如何實例化甲板陣列?每次我實例化一個DeckOfCards對象時,我都需要創建一個Card對象數組並進行填充。 –

+1

將卡片值保存在兩個數組中,並將它們循環到構造函數中。 –

0

刪除線,這將是細:
卡[]甲板=新卡[52];

2

您正在構造函數中再次聲明甲板。我會這樣初始化卡組。迭代通過兩個數組,最簡單的一個。

DeckOfCards(){ 

    suit = ['Hearts','Diamonds','Clubs','Spades']; 
    number=['Ace','One','Two','Three','Four','Five','Six','Seven','Eight','Nine','Ten','Jack','Queen','King']; 

    for (int i=0;i<4;i++){ 
     for (int j=0;j<13;j++){ 
      deck[i+j]=new Card(number[j],suit[i]); 
     } 
    } 
} 

希望這有助於!

1

首先,您不需要在構造函數中再次初始化deck。只需使用您定義的類級變量即可。

二,deck不應該是static,所以刪除那個單詞。

第三,公開構造函數。

最後但並非最不重要的,你應該更聰明地初始化甲板。

public class DeckOfCards { 
    public Card[] deck = new Card[52]; 

    //constructor 
    public DeckOfCards(){ 
     String[] numbers = { "Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King" }; 
     String[] suits = { "Spades", "Clubs", "Diamonds", "Hearts" }; 
     int i = 0; 
     for (String suit: suits) { 
      for (String number: numbers) { 
       deck[i] = new Card(number, suit); 
       i++; 
      } 
     } 
    } 
} 
相關問題