Nested for loops

I need to do a nested for loops, Create a new Card and store it in the array but the only hint i was given was " Using nested enhanced for loops, for (Card suit : cards) and for (Card card : suit), print the card using System.out.println(card);" if im going to print the cards in a deck in order from the TWO of CLUBS to the ACE of SPADES, should i do it that way or another?

`public class Card {
    enum Suit { CLUBS, DIAMONDS, HEARTS, SPADES };
    enum Rank { TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE };

    private final Suit suit;
    private final Rank rank;

    static final Suit[] allSuits = Suit.values();

    static final Rank[] allRanks = Rank.values();

    static final int DECK_COUNT = allSuits.length * allRanks.length;

    public Card( int suit, int rank) {          // Constructor
        this.suit = allSuits[suit];
        this.rank = allRanks[rank];
    }
    @Override
    public String toString() {

        return  rank + " of " + suit;
    }
    public static void main(String[] args){
        Card[][] cards = new Card[Card.allSuits.length][Card.allRanks.length];
        
    }
}`

Every suit has one card of each rank. By looping through each suit, and inside of each suit, each rank, you can create every possible card:

//loop through all of the suits
for suit in Suit:
  //loop through all of the ranks
  for rank in Rank:
    add card of suit and rank to deck (or print it)
  //by this line all cards of suit have been created
//by this line all cards have been created

so if every suit has a card in each rank, that means i can print out a suit and it comes with every rank inside?

At present, Suit is just an enum that contains the suit names… when you loop through the suits, you can print out those names.

When you loop through the ranks via a nested loop inside of the suits, you can print both the current rank, and the current suit (which will eventually give you every card in the deck).

1 Like

would something like this work? for (int row = 0; row < allSuits.length; row++) {
for (int col = 0; col < allRanks[row].length; col++) {
DECK_COUNT[row][col] = row * col;

The goal is to use enhanced for loops, so your solution is counter to the project’s “do it my way” method. You also modify DECK_COUNT as a two-dimensional array, while it is an integer (maybe you meant to reference the cards array?).

//for every suit that exists...
for(suit Suit : Suit.values()){
  //for every rank that exists... 
  //(in this suit simply because we're already in a particular suit by this line)
  for(rank Rank : Rank.values()){
    //Create the card here
  }
}
1 Like

Yeah, I was told to make it a two-dimensional array a long time ago as a requirement and after that it all went downhill for me lmao