asdf
asdf

Reputation: 37

How do I assign more than one of the same String in a loop?

I'm trying to create a grid of 16 (4x4) cards. There are 8 different cards total, so each type of card will be repeated twice.

private static int rows = 4;
private static int columns = 4;

public static Card[][] card = new Card[rows][columns];

public String[][] printHiddenCard() {
    for(int i = 0; i < card.length; i++){
        for(int j = 0; j < card[i].length; j++){
            card[i][j] = new QCard();
        }
    }
}

I can't figure out how to insert two of each QCard, which is one of "?" or my 7 other types of cards (+, -, %, /, etc.), into the object array in random order.

Upvotes: 0

Views: 35

Answers (1)

Paul Boddington
Paul Boddington

Reputation: 37665

I'd make a list of the 16 cards, then shuffle it.

// c1, c2, c3, c4, c5, c6, c7, c8 are your 8 different Cards.
List<Card> allCards = Arrays.asList(c1, c2, c3, c4, c5, c6, c7, c8);
List<Card> list = new ArrayList<>(allCards);
list.addAll(allCards);
Collections.shuffle(list);
int k = 0;
for(int i = 0; i < rows; i++){
    for(int j = 0; j < columns; j++){
        card[i][j] = list.get(k++);
    }
}

Upvotes: 1

Related Questions