简体   繁体   中英

Java: How do I make an array and fill it with objects in my constructor?

I am trying to create a constructor that creates an array and fills that array with custom objects. This array would represent a deck of cards.

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

I feel like this constructor should create an array and fill it with card objects but it doesn't recognize any objects instantiated from DeckOfCards() as arrays.

You are declaring the deck again inside your constructor. I would initialize the deck this way. Iterating through two arrays, simplest one.

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

You have an scope problem since you are declaring again

Card[] deck = new Card[52];

inside the constructor, leaving without effect the global member, do instead use the deck object.... (by the way, no need for static objects...)

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

First, you don't need to initialise deck again in the constructor. Just use the class-level variable you defined.

Second, deck should not be static , so remove that word.

Third, make the constructor public.

And last but not least, you should probably initialise the deck in a smarter way.

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

Delete that line and it will be fine :
Card[] deck = new Card[52];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM