Search code examples
javaarraysunit-testingpoker

Basic Poker Program - Printing Deck


I'm working on a poker project that just deals the 5 top cards from a shuffled deck and lets the user to reject all, some, or none. I understand that there should be ideally 2-3 classes, one with the actual main and the other two being the card and deck. I have created the Deck class and a very basic Tester program that is just supposed to print the shuffled cards. However, when I print the deck, I get something along the lines of "Deck@###d##a". What am I doing wrong?

import java.util.Random;

public class Deck {
// Constructing a deck from two arrays
String[] suit = { "Clubs", "Diamonds", "Hearts", "Spades" };
String[] rank = { "Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King" };
String[] deck = new String[suit.length * rank.length];

// Storing public variables
int suits = suit.length;
int ranks = rank.length;
int deckSize = deck.length;

public Deck()
{
    for(int i = 0; i < suits; i++)
    {
        for(int j = 0; j < ranks; j++)
        {
            deck[ranks*i + j] = rank[j] + " of " + suit[i];
        }
    }
}

// Fisher-Yates Shuffle 
public void shuffle()
{
    Random rand = new Random();
    for (int i = 0; i < deckSize; i++) 
    {
        int x = rand.nextInt(deckSize);
        String temp = deck[x];
        deck[x] = deck[i];
        deck[i] = temp;
    }

}

}

And the tester class:

import java.util.Scanner;

public class DeckTester {
public static void main(String[] args) {
    Deck deck = new Deck();

    System.out.println(deck);
}

}

Output: Deck@###d###a


Solution

  • You're seeing the default `toString() method from the Object class, and you're finding that it's not too helpful. You're also not creating a Card or a true Deck class and so you can't give any class a decent toString() method.

    Solutions:

    • Create a Card class.
    • Give it a rank and a value field.
    • Give it a toString() method.
    • Create a Deck class
    • Give it a collection of Cards.
    • Give it a decent toString() method.

    e.g.,

    // for Deck
    @Override 
    public String toString() {
       StringBuilder sb = new StringBuilder();
       for (Card card: cards) {
          sb.append(card.toString() + ", ");
       }
       return sb.toString();
    }