JAVA每日一題06

這個題目感覺有意思,大家分享一下哦.

題目:編寫程序利用Random類的對象的鏈表中一隨機的順序存儲一副52張的紙牌。用含有連個字符的字符串代表紙牌,例如“1C”表示梅花A,”JD”表示方片J等。從棧中輸出4手牌,每手牌有13張紙牌。

package com.tengfei.lesson06; 
import java.util.Vector;
import java.util.LinkedList;
import java.util.Random;
import java.util.ListIterator;

public class DealCards {
  public static void main(String[] args) {
    String[] suits = {"C", "D", "H", "S"};
    String[] cardValues = { "1","2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"};

    int cardsInDeck = 52;
    Vector<String> deck = new Vector<String>(cardsInDeck);
    LinkedList<String> shuffledDeck = new LinkedList<String>();
    Random chooser = new Random();             // Card chooser

    // Load the deck
    for(String suit : suits) {
      for(String cardValue : cardValues) {
        deck.add(cardValue+suit);
      }
  }

    // Select cards at random from the deck to transfer to shuffled deck
    int selection = 0;                        // Selected card index
    for(int i = 0 ; i<cardsInDeck ; i++) {
      selection = chooser.nextInt(deck.size());
      shuffledDeck.add(deck.remove(selection));
    }
    
    // Deal the cards from the shuffled deck into four hands
    StringBuffer[] hands = { new StringBuffer("Hand 1:"), new StringBuffer("Hand 2:"),
                             new StringBuffer("Hand 3:"), new StringBuffer("Hand 4:")};
    ListIterator cards = shuffledDeck.listIterator();
   
    while(cards.hasNext()) { 
      for(StringBuffer hand : hands) {
        hand.append(' ').append((String)(cards.next()));
      }
    }

    // Display the hands
    for(StringBuffer hand : hands) {
      System.out.println(hand.toString());
    }
  }
}

 

 

 

發佈了17 篇原創文章 · 獲贊 8 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章