• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 295
  • Last Modified:

random card program

my question is how do I write a program that will randomly pull a card from a deck of cards.  I can use numbers or characters to repersent the face values and strings to represent the suits.  How in the world do I do this.

I am using java 1.4 if that makes a difference
0
ZonkCarza
Asked:
ZonkCarza
  • 3
  • 2
  • 2
  • +5
2 Solutions
 
CEHJCommented:
Generate a random number to use as an index into the deck (card collection)
0
 
objectsCommented:
Put your cards in a List and 'shuffle' the list. You can then just takes cards off the top of the list.

// Populate your deck of cards

ArrayList deck = new ArrayList();
for (int i=0; i<52; i++)
{
   // add next card to deck
}

// Shuffle the deck

Collections.shuffle(deck);

// Take the cards from the 'top' of the deck

Object a = list.remove(0);
Object b = list.remove(0);
Object c = list.remove(0);
0
 
drmxCommented:
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class RandomCard {
  public static void main(String[] args) {
    Random rand = new Random();
    List deck = createDeck();
    while (deck.size() > 0) {
      int randIdx = Math.abs(rand.nextInt()) % deck.size();
      String card = (String) deck.get(randIdx);
      deck.remove(randIdx);
      System.out.println("Card: " + card);
    }
  }
  public static List createDeck() {
    List deck = new ArrayList();
    // Now just deck.add("9 Hearts"); deck.add("10 Hearts");
    // This will create the deck of cards, which is just a
    // list of strings
    deck.add("9 Hearts");
    deck.add("10 Hearts");
    deck.add("4 Clubs");
    deck.add("5 Clubs");
    return deck;
  }
}
0
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
FummaciousCommented:
Try this:

public class Deck
{
    private ArrayList deck;
    private static final suits[] = {"Diamonds", "Clubs", "Hearts", "Spades"};
    private static final cards[] = {"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King" };

    public Deck()
    {
        deck = new ArrayList(52);
        resetDeck();
    }
    public void resetDeck()
    {
        boolean cards[] = new boolean[52];
        for (int i = 0; i < 52; i++)
        {
            cards[i] = true;
        }
        for (int i = 0; i < 52; i++)
        {
            int cardNum = Random.nextInt(52);
            while (cards[cardNum] == false)
            {
                cards[cardNum] = false;
                deck.add(new Integer(cardNum));
            }
        }
    }

    public int dealCard()
    {
        if (cardsInDeck() == 0)
            return -1;
        Integer i = (Integer)deck.remove(0);
        return i;
    }

    public int cardsInDeck()
    {
        return deck.size();
    }

    public String suit(int cardNum)
    {
        return suits[cardNum/13];
    }
    public String cardOrdinal(int cardNum)
    {
        return cards[cardNum%13];
    }
    public String cardName(int cardNum)
    {
        return cardOrdinal(cardNum) + " of " + suit(cardNum);
    }
}
0
 
ZonkCarzaAuthor Commented:
Thanks for all the input but I ended up figuring out a much easier way to do this.  If you are interested to know what I did... here it is

public class card {

     public static void main(String args[]) {


     String Suit = "";
       int n = (int) (Math.random() * 13 + 1);
       int c = (int) (Math.random() * 4 + 1);


    if (c == 1) {
      Suit = "Hearts";
    }
    else if (c == 2) {
      Suit = "Clubs";
    }
    else if (c == 3) {
      Suit = "Diamonds";
    }
    else {
      Suit = "Spades";
    }

 
System.out.println("Your Random Card is the " + n + " of " + Suit);

 }
}
0
 
objectsCommented:
your question said you were dealing with a "deck of cards".
Your code will work fine if you only want a single card, but probably not useful for anything more than that.

0
 
CEHJCommented:
Your Random Card is the 1 ofDiamonds

Your Random Card is the 13 ofSpades
0
 
TimYatesCommented:
LOL
0
 
Bob_EverardCommented:
A very simple improvement on your solution, bearing in mind that nobody would actually want to do it in this inflexible way is:

public class draw {
   public static void main( String[] args ) {
      String[] suits = { "Clubs", "Diamonds", "Hearts", "Spades" };
      String[] cards = { "Ace", "2", "3", "4", "5", "6", "7",
                         "8", "9", "10", "Jack", "Queen", "King" };
      int r = (int)(Math.random() * 52);
      System.out.println( "Your random card is the " +
                          cards[ r % 13 ] + " of " + suits[ r / 13 ] );
   }
}

A proper implementation would naturally be to allow specification of how many cards to draw, whether or not the drawn card(s) should be replaced in the deck, whether or not the deck should be shuffled between draws, and so on.
0
 
CleanupPingCommented:
ZonkCarza:
This old question needs to be finalized -- accept an answer, split points, or get a refund.  For information on your options, please click here-> http:/help/closing.jsp#1 
EXPERTS:
Post your closing recommendations!  No comment means you don't care.
0
 
TimYatesCommented:
No comment has been added lately, so it's time to clean up this TA.
I will leave a recommendation in the Cleanup topic area that this question is:

Split between objects and CEHJ.

Please leave any comments here within the next seven days.

PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!

TimYates
EE Cleanup Volunteer
0
 
CEHJCommented:
:-)
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 3
  • 2
  • 2
  • +5
Tackle projects and never again get stuck behind a technical roadblock.
Join Now