`

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());
    }
  }
}

 

 

 

16
3
分享到:
评论
6 楼 virue 2009-03-23  
写的相当不错
5 楼 lqy1987lqy 2009-03-19  
k830530 写道

while(cards.hasNext()) {&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; for(StringBuffer hand : hands) {&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; hand.append(' ').append((String)(cards.next()));&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; } 请问这是JDK那个版本的for循环语法啊?什么含义啊,是吧52张牌平均分给4“手”吗?

是for each 语句
4 楼 yohofoyu 2009-03-19  
可不可以把他加到一个界面里面啊 做成一个小游戏 呵呵
3 楼 k830530 2009-03-19  
while(cards.hasNext()) {   
      for(StringBuffer hand : hands) {  
        hand.append(' ').append((String)(cards.next()));  
      }  
    }


请问这是JDK那个版本的for循环语法啊?什么含义啊,是吧52张牌平均分给4“手”吗?
2 楼 jythoner 2009-03-19  
刚才去顶你的每日一题帖子,内容为:"顶!支持!呵呵",结果被评为差贴,扣了我30分,hoho
在这个帖子中再顶!
1 楼 beekimlin 2009-03-18  
呵呵,很有趣,感谢楼主分享

相关推荐

Global site tag (gtag.js) - Google Analytics