?
Solved

random card program

Posted on 2003-03-05
13
Medium Priority
?
294 Views
Last Modified: 2008-03-17
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
Comment
Question by:ZonkCarza
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
  • 2
  • +5
13 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 8075734
Generate a random number to use as an index into the deck (card collection)
0
 
LVL 92

Expert Comment

by:objects
ID: 8075987
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
 

Expert Comment

by:drmx
ID: 8075989
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
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 

Expert Comment

by:Fummacious
ID: 8076018
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
 

Author Comment

by:ZonkCarza
ID: 8076521
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
 
LVL 92

Accepted Solution

by:
objects earned 200 total points
ID: 8076794
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
 
LVL 86

Assisted Solution

by:CEHJ
CEHJ earned 200 total points
ID: 8079117
Your Random Card is the 1 ofDiamonds

Your Random Card is the 13 ofSpades
0
 
LVL 35

Expert Comment

by:TimYates
ID: 8079305
LOL
0
 
LVL 2

Expert Comment

by:Bob_Everard
ID: 8226269
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
 

Expert Comment

by:CleanupPing
ID: 9058896
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
 
LVL 35

Expert Comment

by:TimYates
ID: 9762300
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
 
LVL 86

Expert Comment

by:CEHJ
ID: 9814058
:-)
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
In this post we will learn different types of Android Layout and some basics of an Android App.
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
This video teaches viewers about errors in exception handling.
Suggested Courses
Course of the Month9 days, 17 hours left to enroll

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question