提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
卡洗牌和交易。
import java.security.SecureRandom; public class Main { // execute application/**from N o w J a v a . c o m - 时 代 Java**/ public static void main(String[] args) { DeckOfCards myDeckOfCards = new DeckOfCards(); myDeckOfCards.shuffle(); // place Cards in random order // print all 52 Cards in the order in which they are dealt for (int i = 1; i <= 52; i++) { // deal and display a Card System.out.printf("%-19s", myDeckOfCards.dealCard()); if (i % 4 == 0) // output a newline after every fourth card System.out.println(); } /** 来 自 N o w J a v a . c o m - 时代Java **/ } } class Card { private final String face; // face of card ("Ace", "Deuce", ...) private final String suit; // suit of card ("Hearts", "Diamonds", ...) // two-argument constructor initializes card's face and suit public Card(String face, String suit) { this.face = face; this.suit = suit; } // return String representation of Card public String toString() { return face + " of " + suit; } } class DeckOfCards { private Card[] deck; // array of Card objects private int currentCard; // index of next Card to be dealt (0-51) private static final int NUMBER_OF_CARDS = 52; // constant # of Cards // random number generator private static final SecureRandom randomNumbers = new SecureRandom(); // constructor fills deck of Cards 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]; // create array of Card objects currentCard = 0; // first Card dealt will be deck[0] // populate deck with Card objects for (int count = 0; count < deck.length; count++) deck[count] = new Card(faces[count % 13], suits[count / 13]); } public void shuffle()