集册 Java实例教程 卡改组和与Collections方法改组的处理。

卡改组和与Collections方法改组的处理。

欢马劈雪     最近更新时间:2020-01-02 10:19:05

398
卡片洗牌和处理收集方法洗牌。

import java.util.List;

import java.util.Arrays;

import java.util.Collections;/**来 自 时代Java - nowjava.com**/


// class to represent a Card in a deck of cards

class Card 

{   

   public static enum Face {Ace, Deuce, Three, Four, Five, Six,

      Seven, Eight, Nine, Ten, Jack, Queen, King};

   public static enum Suit {Clubs, Diamonds, Hearts, Spades};


   private final Face face; 

   private final Suit suit;

   

   // constructor

   public Card(Face face, Suit suit) 

   {  

       this.face = face;

       this.suit = suit; 

   } /*来自 时代Java - nowjava.com*/

   

   // return face of the card

   public Face getFace() 

   {

      return face; 

   } 


   // return suit of Card

   public Suit getSuit() 

   {

      return suit; 

   } 


   // return String representation of Card

   public String toString()

   {

      return String.format("%s of %s", face, suit);

   } 

} 


// class DeckOfCards declaration

public class Main 

{

   private List<Card> list; // declare List that will store Cards


   // set up deck of Cards and shuffle

   public Main()

   {

      Card[] deck = new Card[52];

      int count = 0; // number of cards


      // populate deck with Card objects

      for (Card.Suit suit : Card.Suit.values())  

      {

         for (Card.Face face : Card.Face.values())   

         {

            deck[count] = new Card(face, suit);

            ++count;

         } 

      } 


      list = Arrays.asList(deck); // get List

      Collections.shuffle(list);  // shuffle deck

   } // end DeckOfCards constructor


   // output deck

   public void printCards()

   {

      
展开阅读全文