Java 怎么实现洗牌和发牌

2019年7月3日21:28:46 评论 73

1.简介

Java 怎么实现洗牌和发牌?——请看下文。

2.代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */
import java.security.SecureRandom;
public class Main
{
   
   public static void main(String[] args)
   {
      DeckOfCards myDeckOfCards = new DeckOfCards();
      myDeckOfCards.shuffle(); 
      
      
      for (int i = 1; i <= 52; i++)
      {
         
         System.out.printf("%-19s", myDeckOfCards.dealCard());

     if (i % 4 == 0) 
        System.out.println();
      } 
   } 
}

class Card 
{
   private final String face; 
   private final String suit; 

   
   public Card(String face, String suit)
   {
      this.face = face;
      this.suit = suit; 
   } 

   
   public String toString() 
   { 
      return face + " of " + suit;
   } 
}
class DeckOfCards
{
   private Card[] deck; 
   private int currentCard; 
   private static final int NUMBER_OF_CARDS = 52; 
   
   private static final SecureRandom randomNumbers = new SecureRandom();

   
   public DeckOfCards()
   {
      String[] faces = {"Ace", "Deuce", "Three", "Four", "Five", "Six", 
         "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"};
      String[] suits = {"Hearts", "Diamonds", "Clubs", "Spades"};

      deck = new Card[NUMBER_OF_CARDS]; 
      currentCard = 0; 

      
      for (int count = 0; count < deck.length; count++) 
         deck[count] = 
            new Card(faces[count % 13], suits[count / 13]);
   } 

   public void shuffle()
   {
      currentCard = 0; 
      for (int first = 0; first < deck.length; first++) 
      {
         int second =  randomNumbers.nextInt(NUMBER_OF_CARDS);
         Card temp = deck[first];        
         deck[first] = deck[second];   
         deck[second] = temp;            
      } 
   } 
   public Card dealCard()
   {
      if (currentCard < deck.length)
         return deck[currentCard++]; 
      else        
         return null; 
   } 
}

 

3.总结

示例代码演示了 Java 怎么实现洗牌和发牌,具体步骤参见示例代码。

  • A+
所属分类:

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: