简体   繁体   中英

Filling a Java array with elements produced in another class

I'm trying to fill a deck of cards in my "Deck" class with cards created in my "Card" class. When I print the result in my Deck class, I get 52 "null"s, which tells me the two are communicating, just not very well. I've copied the code below. Where am I going wrong? Thanks!

public class Card {
    public String cardName;
    private int[] cardValue = {(Integer) null, 1, 2, 3, 4, 5, 6, 7, 8, 
        9, 10, 11};
    private String[] cardSuit = {"C", "D", "H", "S"};


    public Card(String cardName, int[] cardValue, String[] cardSuit) {
        this.cardName = cardName;
        this.cardValue = cardValue;
        this.cardSuit = cardSuit;
    }
    public String makeCard(int[] cardValue, String[] cardSuit) {
        for(int i = 0; i < 12; i++) {
            for(int j = 0; j < 4; j++) {
                cardName = cardValue[i] + cardSuit[j];
                j++;
            }
            i++;
        }
        return cardName;
    }   
}
import java.util.Arrays;

public class Deck {

    public static String[] cardDeck = new String[52];

    public String[] makeDeck(String cardName) {
        for(int i =0; i < 52; i++) {
            cardDeck[i] = cardName;
            i++;
        }

        Arrays.fill(cardDeck, cardName);
        return cardDeck;
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(cardDeck));
    }
}

You create a new string array with String[] cardDeck = new String[52]; but you never assign any values to this array. String is an object and initialized with null. So only null will be printed. You never call any method of any class nor are you initializing deck and card.

Your two classes are still independent. I've modified your code as follows:

public class Card {
    private String[] cardDeck = new String[52];
    private int[] cardValue = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};
    private String[] cardSuit = {"C", "D", "H", "S"};

    public String[] makeDeck() {
        int c = 0;
        for (int i = 0; i < cardValue.length; i++) {
            for (int j = 0; j < cardSuit.length; j++) {
                cardDeck[c] = cardSuit[j] + cardValue[i];
                c++;
            }
        }
        return cardDeck;
    }
}
import java.util.Arrays;

public class Deck {
    public static void main(String[] args) {
        Card card = new Card();
        System.out.println(Arrays.toString(card.makeDeck()));
    }
}

The makeDeck method in Card class will now initialize the deck by iterating over each card value in a deck and the result will be appended to the cardDeck String array.

Further, the Deck Class calls this method and displays the deck.

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