Reputation: 13
so this is my deck class populating a deck of cards
/**
Constructs a deck with 52 cards
*/
public Deck() {
int k = 0; // counter to keep track of elements in the deck array
// nested for loops to populate the deck of cards with 4 suits and 13 possible rankings
for (int i = 1; i < SUITS; i++) {
for (int j = 1; j < RANKS; j++) {
deckOfCards[k] = new Card(i, j); // adds the cards to the deck array
k++; // increment the elements counter by 1
System.out.println(deckOfCards[k]);
}
}
}
this is my card class even though I'm almost positive there isn't anything wrong with this part
public class Card {
private int rank;
private int suit;
/**
* @param suit the suit of the card in a deck
* @param rank the rank of the card in a deck
*/
public Card(int suit, int rank) {
this.rank = rank; // initializing the rank
this.suit = suit; // initializing the suit
}
When I print out the cards in the deck, I get null
returned. Any ideas why?
Upvotes: 1
Views: 88
Reputation: 39
I'm guessing you already initialized deckOfCards, so your problem is that your incrementing k before printing the card. If you remove k++ and change println(deckOfCards[k]) to println(deckOfCards[k++]) it should do the trick because it uses k and then increments it.
P.S: sorry for no code format, I'm doing this on my phone
Upvotes: 0
Reputation: 5232
deckOfCards[k] = new Card(i, j);
k++;
System.out.println(deckOfCards[k]);
You're setting deckOfCards[k]
but printing deckOfCards[k+1]
.
Upvotes: 5