Card Shuffling and Dealing Simulation

Source: Internet
Author: User
Tags shuffle

Card has a face (e.g ., "Ace", "Deuce", "Three ",..., "Jack", "Queen", "King") and a suit (e.g ., "Hearts", "Diamonds", "Spades", "Clubs ").


//Cards.javapublic class Cards {private String face;private String suit;public Cards(String cardFace, String cardSuit){face = cardFace;suit = cardSuit;}public String toString(){return  "[" + suit + "] " + face ;}}

//DeckOfCards.javaimport java.util.Random;public class DeckOfCards {private int currentCard;private Cards deck[];private Random r;private final int NUMBER_OF_CARDS = 52;public DeckOfCards (){String[] face = {"A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"};String[] suit = {"Hearts", "Diamonds", "Clubs", "Spades"};deck = new Cards[NUMBER_OF_CARDS];currentCard = 0;r = new Random();for(int i=0; i<deck.length; i++){deck[i] = new Cards(face[i%13], suit[i/13]);}}public void shuffle(){for(int first=0; first<deck.length; first++){int second = r.nextInt(NUMBER_OF_CARDS);Cards tmp = deck[first];deck[first] = deck[second];deck[second] = tmp;}}public Cards dealCard(){if(currentCard < deck.length)return deck[currentCard++];else return null;}}

//DeckOfCardsTest.javapublic class DeckOfCardsTest {public static void main(String[] args){DeckOfCards deck = new DeckOfCards();deck.shuffle();for(int i=0; i<13; i++){//System.out.printf("%-20s%-20s%-20s%-20s\n", //deck.dealCard(), deck.dealCard(), deck.dealCard(), deck.dealCard());System.out.println(deck.dealCard().toString() + "\t" + deck.dealCard().toString() + "\t" +deck.dealCard().toString() + "\t" + deck.dealCard().toString());}}}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.