I am trying to build a blackjack game. I have created a deck, now I want to display it.
I know I’m doing something wrong because I cannot access displayStack within CardStack class. Also, I have a feeling that I’m not doing inheritance correctly. How could I fix this?
Here is my code:
public class CreateCardDeck {
int deckSize = 52;
CardStack cardStack = new CardStack(deckSize);
public void CreateDeck() {
String[] suit = {"clubs", "diamonds", "hearts", "spades"};
int[] rank = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};
for (int i = 0; i < rank.length; i ++) {
for (int j = 0; j < suit.length; j++) {
cardStack.push(suit[j], rank[i]);
}
}
}
}
Card class:
class Card {
String suit;
int rank;
Card(String suit, int rank) {
this.suit = suit;
this.rank = rank;
}
public String getSuit() {
return suit;
}
public String getRank() {
String nameTheRank;
if (rank == 1)
nameTheRank = "Ace";
else if (rank == 11)
nameTheRank = "Jack";
else if (rank == 12)
nameTheRank = "Queen";
else if (rank == 13)
nameTheRank = "King";
else
nameTheRank = String.valueOf(rank);
return nameTheRank;
}
}
CardStack class:
class CardStack {
public void displayDeck() {
for (int i = 0; i < stackArray.length; i ++)
System.out.println(stackArray[i]);
}
}
The Main Class:
public class MainClass {
public static void main(String[] args) throws IOException {
CreateCardDeck c = new CreateCardDeck();
c.CreateDeck();
// How to display my deck?
}
}
I would redesign your types to start with.
CreateCardDecksounds like it should really be a static method calledcreateDeckwithin aCardDeckor possibly justCardtype. It also sounds like the knowledge of suits and number shouldn’t really be part of that method. Cards are often used as a demonstration of enums in Java – one enum for the values (ace to king) and one for the suits.Think about what it really means to have an instance of
CreateCardDeck– does that really make sense to you? It feels more like a verb (a method) than a noun (a type).Now you could have a
CardDeckFactoryor something similar – but then I wouldn’t expect the deck to be part of the state of the object; it would just be returned by a method.