Java 用LinkdeList实现52张扑克牌

LinkdeList实现52张扑克牌(不含大小王)的洗牌功能。提示:花色 ,和数字分别用数组存储。

 

 

import java.util.LinkedList;
import java.util.Random;

class Poker{
    
    String color;//花色
    String  num;//数字
    
    public Poker(String color,String num){
        
        this.color = color;
        this.num = num;
    }
    
    @Override
    public String toString() {
        // TODO Auto-generated method stub
        return "{"+color+num+"}";
    }
}

public class HomeWork3 {

    /**
     * @param args
     * 用LinkdeList实现52张扑克牌(不含大小王)的洗牌功能。
     * 提示:花色 ,和数字分别用数组存储。
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
       // 1.创建扑克牌
        LinkedList list = creatPoker();
        //2.洗牌
        shufflePoker(list);
        //3.显示
        showPoker(list);
        
        //4.发牌的功能。
        
    }
    
    //洗牌的功能
    public static void shufflePoker(LinkedList poker){
        
        //1.产生一个随机数
        Random rangdom =  new  Random();
        
        for(int i = 0 ;i<100;i++){
            
            //随机获取两个索引值:
            int index1 = rangdom.nextInt(poker.size());
            int index2 = rangdom.nextInt(poker.size());
            Poker p1 = (Poker) poker.get(index1);
            Poker p2 = (Poker) poker.get(index2);
            //交换用set方法
            poker.set(index1, p2);
            poker.set(index2, p1);
            
        }
        
    }
    
    public static void showPoker(LinkedList list){
        
        for(int i = 0;i<list.size();i++){
            
            System.out.print(list.get(i));
            if( i % 13 == 12){
                
                System.out.println();
            }
            
        }
        
    }
    
    public static LinkedList creatPoker(){
        //创建集合对象用来存放扑克牌
        LinkedList list = new LinkedList();
        //定义花色和数字
        String[] colors = {"黑桃","红桃","方块","梅花"};
        String[] nums = {"A","2","3","4","5","6","7","8","9","10","J","Q","K"};
        
        for(int i = 0 ;i<nums.length ;i++){
            
            for(int j = 0;j<colors.length;j++){
                
                list.add(new Poker(colors[j], nums[i]));
            }
        }
        
        return list;
    }

}

 

posted @ 2016-12-19 19:52  随行-LV  阅读(1218)  评论(0编辑  收藏  举报