Question

So I am creating this BlackJack Java game that uses many different classes to learn how to program using OO. I'm really stuck on this one particular part however, getting the code to display the correct card in the hand. It just displays a weird string such as com.game.blackjack.Hand@18e2b22, or has a different display of characters. Wondering how this can be converted into an actual card value and rank?

public class Suit {

public static final int SPADE = 0, HEART = 1, DIAMOND = 2, CLUB = 3;

/**
 * Maps the names for the suits  as a string.
 */
private Map<Integer, String> suitMap = new HashMap<Integer, String>();

/**
 * ID for the suit
 */
private int suitId = 0;

/**
 * sets the id for the suit to get.
 */
public Suit(int suitId) {
    suitMap.put(SPADE, "Spades");
    suitMap.put(HEART, "Hearts");
    suitMap.put(DIAMOND, "Diamonds");
    suitMap.put(CLUB, "Clubs");

    this.suitId = suitId;
}


public String toString() {
    return suitMap.get(suitId);
}

/**
 * @param suitId
 * @return suitMap
 */
public String getSuitNameById(int suitId) {
    return suitMap.get(suitId);
}

/**
 * @return id of suit
 */
public String getSuitName() {
    return suitMap.get(suitId);
}

/**
 * @return the suitId
 */
public int getSuitId() {
    return suitId;
}

/**
 * @param suitId the suitId to set
 */
public void setSuitId(int suitId) {
    this.suitId = suitId;
}

/**
 * @return the suitMap
 */
public Map<Integer, String> getSuitMap() {
    return suitMap;
}

/**
 * @param suitMap the suitMap to set
 */
public void setSuitMap(Map<Integer, String> suitMap) {
    this.suitMap = suitMap;
}

}

public class Card {

private boolean stateOfCard = false;

/**
 * Gives the constant values to ace jack queen and king for being special
 * types of cards.
 */
public final static int ACE = 1, JACK = 11, QUEEN = 12, KING = 13;

/**
 * Maps names to the ace jack queen and king cards.
 */
private Map<Integer, String> nameMap = new HashMap<Integer, String>();

/**
 * Rank or type of card (2-9, J,Q,K, A)
 */
private String cardRank = null;

/**
 * Card suit
 */
private Suit suit = null;

/**
 * Numeric value of the card
 */
private int cardValue = 0;

/**
 * Gives you the suit, cardRank, and the cardValue
 */
public Card(Suit suit, String cardRank, int cardValue) {
    nameMap.put(ACE, "Ace");
    nameMap.put(JACK, "Jack");
    nameMap.put(QUEEN, "Queen");
    nameMap.put(KING, "King");

    if (cardValue >= 11 || cardValue == 1) cardRank = nameMap.get(cardValue);

    this.suit = suit;
    this.cardRank = cardRank;
    this.cardValue = cardValue;
}
/**
 * Displays to user the rank and suit of the card.
 */
public String toString() {
    return cardRank + " of " + suit.getSuitName();
}

/**
 * @return the cardRank
 */
public String getCardRank() {
    return cardRank;
}

/**
 * @param cardRank the cardRank to set
 */
public void setCardRank(String cardRank) {
    this.cardRank = cardRank;
}

/**
 * @return the suit
 */
public Suit getSuit() {
    return suit;
}

/**
 * @param suit the suit to set
 */
public void setSuit(Suit suit) {
    this.suit = suit;
}

/**
 * @return the cardValue
 */
public int getCardValue() {
    return cardValue;
}

/**
 * @param cardValue the cardValue to set
 */
public void setCardValue(int cardValue) {
    this.cardValue = cardValue;
}

/**
 * @return the nameMap
 */
public Map<Integer, String> getNameMap() {
    return nameMap;
}

/**
 * @param nameMap the nameMap to set
 */
public void setNameMap(Map<Integer, String> nameMap) {
    this.nameMap = nameMap;
}
/**
 * @return the stateOfCard
 */
public boolean isStateOfCard() {
    return stateOfCard;
}

/**
 * @param stateOfCard the stateOfCard to set
 */
public void setStateOfCard(boolean stateOfCard) {
    this.stateOfCard = stateOfCard;
}

}

public class Deck {

/**
 * Deck of cards created
 */
private ArrayList<Card> deck = new ArrayList<Card>();

/**
 * Keeps track of the cards that are dealt and no longer available
 */
private List<Card> cardUsed = new ArrayList<Card>();

/**
 * The array of cards in a set. Can be shuffled and drawn from. Deck of any #.
 * @param cards 
 */
public Deck(int numCards) {
    this.createDeck(numCards, 4);
}

/**
 * creates a deck that has cards in it with 4 suits of each 13 cards.
 * @param numCards
 * @param numSuits
 */
private void createDeck(int numCards, int numSuits) {
    deck = new ArrayList<Card>();
    cardUsed = new ArrayList<Card>();
    if ((numCards % numSuits) > 0) return;
    for (int i=0; i < numSuits; i++) {

        for(int j=1; j <= (numCards / numSuits); j++) {
            deck.add(new Card(new Suit(i), j + "", j));
        }
    }
}

/**
 * Deals a card to the hand. Sends dealt card to the cardUsed list so that 
 * a used card will not be drawn again unless deck is shuffled.
 * @return dealtCard
 */
public Card dealCard( ) {

    Card dealtCard = null;
    if (deck.size() == 0){
        deck.addAll(cardUsed);
        this.shuffle();
        cardUsed = new ArrayList<Card>();
    }

    dealtCard = deck.get(0);
    deck.remove(0);
    cardUsed.add(dealtCard);

    return dealtCard;
}

/**
 * Shuffles the cards after every round.
 */
public void shuffle() {
    Collections.shuffle(deck);
}

/**
 * @return the deck
 */
public ArrayList<Card> getDeck() {
    return deck;
}

/**
 * @param deck the deck to set
 */
public void setDeck(ArrayList<Card> deck) {
    this.deck = deck;
}

/** 
 * Returns the number of used cards
 * @return
 */
public int getNumUsedCards() {
    return cardUsed.size();
}

/**
 * @return the cardUsed
 */
public List<Card> getCardUsed() {
    return cardUsed;
}

/**
 * @param cardUsed the cardUsed to set
 */
public void setCardUsed(List<Card> cardUsed) {
    this.cardUsed = cardUsed;
}

}

public class Hand {

private ArrayList<Card> hand = new ArrayList<Card>();
int total = 0;

/**
 * A list of cards that can be defined as hand. Player has a list of these
 * cards in a hand.
 */
public Hand(){

}

public boolean isAce() {


    return false;
}

public boolean discardHand(){
    if (hand.isEmpty()) {
        hand = new ArrayList<Card>();
    }
    return false;
}
/**
 * Adds the card to the hand in a list of cards.
 * @param c
 */
public void addCard(Card c) {
    this.hand.add(c);
}

/**
 * Gets the place value of the card in the hand.
 * @param index
 * @return index of card in hand
 */
public Card getPosition(int index){
    return hand.get(index);
}

/**
 * Gets how many cards are in the player's hand.
 * @return hand size
 */
public int handCardCount(){
    return hand.size();
}

/**
 * @return the total
 */
public int getTotal() {
    return total;
}

/**
 * @param total the total to set
 */
public void setTotal(int total) {
    this.total = total;
}

/**
 * @return the hand
 */
public ArrayList<Card> getHand() {
    return hand;
}

/**
 * @param hand the hand to set
 */
public void setHand(ArrayList<Card> hand) {
    this.hand = hand;
}

}

public class Player extends Person {

private Hand myCards = new Hand();
private int playerCashAmount = 100;

public Player() {

}

public Player(String name) {
    this.name = name;
}

/**
 * Gets the name of the user from the parent class
 */
public String getName() {
    return super.getName();
}


/**
 * @return the playerCashAmount
 */
public int getPlayerCashAmount() {
    return playerCashAmount;
}

/**
 * @param playerCashAmount the playerCashAmount to set
 */
public void setPlayerCashAmount(int playerCashAmount) {
    this.playerCashAmount = playerCashAmount;
}

/**
 * @return the myCards
 */
public Hand getMyCards() {
    return myCards;
}

/**
 * @param myCards the myCards to set
 */
public void setMyCards(Hand myCards) {
    this.myCards = myCards;
}

}

public class Dealer extends Person {

private String dealCards = null; 
private String playCards = null;
private String shuffleDeck = null;
private Hand computerCards = new Hand();

/**
 * 
 */
public Dealer() {

}

/**
 * @return the dealCards
 */
public String getDealCards() {
    return dealCards;
}

/**
 * @param dealCards the dealCards to set
 */
public void setDealCards(String dealCards) {
    this.dealCards = dealCards;
}

/**
 * @return the playCards
 */
public String getPlayCards() {
    return playCards;
}

/**
 * @param playCards the playCards to set
 */
public void setPlayCards(String playCards) {
    this.playCards = playCards;
}

/**
 * @return the shuffleDeck
 */
public String getShuffleDeck() {
    return shuffleDeck;
}

/**
 * @param shuffleDeck the shuffleDeck to set
 */
public void setShuffleDeck(String shuffleDeck) {
    this.shuffleDeck = shuffleDeck;
}

/**
 * @return the computerCards
 */
public Hand getComputerCards() {
    return computerCards;
}

/**
 * @param computerCards the computerCards to set
 */
public void setComputerCards(Hand computerCards) {
    this.computerCards = computerCards;
}

}

public class Person {

protected String name = null; Hand h = new Hand();

/**
 * 
 */
public Person() {

}

/**
 * @return the name
 */
public String getName() {
    return name;
}

/**
 * @param name the name to set
 */
public void setName(String name) {
    this.name = name;
}

/**
 * @return the h
 */
public Hand getH() {
    return h;
}

/**
 * @param h the h to set
 */
public void setH(Hand h) {
    this.h = h;
}

}

public class GameEngine {

static Scanner in = new Scanner(System.in);
private Dealer dealer = null;
List<Player> players = new ArrayList<Player>();
Hand h = new Hand();
Person p = new Player();
Player pl = new Player();
int bet = 0;
Deck d = null;
int num = 0;

public GameEngine() {

}

/**
 * Plays the game by creating a new instance of the gameplay class.
 * @param args
 */
public static void main(String[] args) {
    GameEngine ge = new GameEngine();
    ge.gamePlay();
}

/**
 * Game of BlackJack, runs all the methods that it will call to.
 */
public void gamePlay() {
    // States the title of the game.
    //this.welcomeToGame();

    // Shuffles the deck and creates the number of cards for it.
    this.deckStart();

    // Prompts user for number of players.
    //this.howManyPlayers(num);

    // Displays welcome message and asks for user's name.
    //this.greetUser();

    // Deal initial cards
    this.beginCardDeal();

    // Place bet on the current round.
    //this.betAmount(pl, bet);

    // Evaluate, get player choice (stay or hit or bust)
    //this.evaluatePlayer();

    // Evaluate if bust.
    //this.isBust();

    // Deal more cards to each user.
    //this.takeHitOrStay();

    // All players bust / stay.


    // Evaluate winner.


}

/**
 * Initializes the deck and shuffles it.
 */
public void deckStart () {
    d = new Deck(52);
    d.shuffle();
}

/**
 * Displays welcome message to the player.
 */
public void welcomeToGame(){
    System.out.println("This is BlackJack (Double Exposure)\n\n");
}

/**
 * Asks for name input and then welcomes them with name.
 */
public void greetUser() {
    System.out.print("Enter your name: ");
    p.setName(in.next());
    System.out.println("Welcome, " + p.getName() + ".");
}

/**
 * Prompts user to input how many opponents they would like to face in the game of BlackJack.
 * @param num
 */
public void howManyPlayers(int num) {
    players = new ArrayList<Player>();
    System.out.print("How many other players would you like for this game? Enter here: ");
    num = in.nextInt();
    for (int i=0; i < num; i++) {
        players.add(new Player("Player " + i));
        System.out.println(players);
    }
}

/**
 * Asks the player how much money they will bet on the hand.
 * @param pl
 * @param bet
 */
public void betAmount(Player pl, int bet) {
    while (bet == 0 || bet > pl.getPlayerCashAmount()) {
        System.out.print("You have $" + pl.getPlayerCashAmount() + " as of now. Please enter a bet amount: ");
        bet = in.nextInt();
        System.out.println("You are going to bet $" + bet + ".");
        if (bet < 0 || bet > pl.getPlayerCashAmount()) 
            System.out.println("\nYour answer must be between $0 and $" +  pl.getPlayerCashAmount());
        else if (bet == pl.getPlayerCashAmount())
            System.out.println("All in!");
    }
}

/**
 * Deals the cards to each of the players.
 */
public void beginCardDeal () {
    for (int x = 0; x < 2; x++) {
        System.out.print("\nDealer is dealing a card. . . \n");
        d.dealCard();
        System.out.println("\nYour hand: " + pl.getMyCards());
        //System.out.println("New hand value test::: " + pl.getMyCards().addCard(d.dealCard()));
    }
}

/**
 * Checks to see if the player's hand value is over 21. If yes then player
 * loses that round.
 */
public void isBust(){
    if (h.getTotal() > 21) {
        System.out.println("Sorry, you have gone over 21 and busted.");
        int money = pl.getPlayerCashAmount() - bet;
        System.out.println("You lost $"+bet+", and now you have "+money);
    }
}

/**
 * Counts the total value of cards each player holds in their hand.
 */
public void evaluatePlayer(){
    System.out.println("Your hand value is: ");
    System.out.println(pl.getMyCards().getTotal());

}

public String takeHitOrStay(){
    while (pl.getMyCards().getTotal() < 21){
        System.out.println("Would you like to hit[h] or stay[s]? ");
        String choice = in.next();
        if (choice.equalsIgnoreCase("h")){
            pl.getMyCards();
            //System.out.println(pl.getMyCards());
            if (choice.equalsIgnoreCase("s")){
                System.out.println("Null");
                //finish this.
            }
        }
        return choice;
    }
    return null;
}

/**
 * @return the deck
 */
public Deck getDeck() {
    return d;
}

/**
 * @param deck the deck to set
 */
public void setDeck(Deck deck) {
    this.d = deck;
}

/**
 * @return the player
 */
public Player getPlayer() {
    return pl;
}

/**
 * @param player the player to set
 */
public void setPlayer(Player player) {
    this.pl = player;
}

/**
 * @return the dealer
 */
public Dealer getDealer() {
    return dealer;
}

/**
 * @param dealer the dealer to set
 */
public void setDealer(Dealer dealer) {
    this.dealer = dealer;
}

}

The new problem I am having is that the result I am getting is now null of Spades or 0 of Spades as an output. I added a toString() function into the Hand class.

public String toString(){
    return c.getCardValue() + " of " + s.getSuitName();
}

So this has been added to Hand and cleared my first problem of only getting the Hash code for each output. Any ideas on Why I am getting the null of Spades as an output?

Was it helpful?

Solution

You've overridden toString on many classes, but not (yet) on the Hand class. Override toString on Hand to provide your own custom string conversion, or else you'll get the Object implementation of toString, which is to use the class name, an @ sign, and the address of the object.

To quote the Javadocs:

The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

getClass().getName() + '@' + Integer.toHexString(hashCode())

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top