利用LinkedList实现洗牌功能

分2步:

1.生成扑克牌。

2.洗牌。

package com.dongbin.collection;

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

/**
 * 利用LinkedList,完成洗牌的功能。
 * @author dongbin
 *
 */
class Poker{
    private String color;//花色
    private String num;//数字    
    
    public Poker(String color,String num) {
        this.color = color;
        this.num = num;
    }
    
    @Override
    public String toString() {        
        return color+num;
    }
}

public class Demo2 {

    public static void main(String[] args) {
        //生成扑克牌
        String [] colors = {"红桃","黑桃","方块","梅花"};
        String [] nums = {"A","2","3","4","5","6","7","8","9","10","J","Q","K"};
    
        LinkedList<Poker> pokers = new LinkedList<Poker>();
        pokers.add(new Poker("", "大王"));
        pokers.add(new Poker("", "小王"));
        for(int i=0;i<colors.length;i++){
            for(int j=0;j<nums.length;j++){
                pokers.add(new Poker(colors[i], nums[j]));
            }
        }    
        
        //洗牌
        Random random = new Random();
        for(int i=0;i<1000;i++){
            int index1 = random.nextInt(pokers.size());
            int index2 = random.nextInt(pokers.size());
            
            Poker poker1 = (Poker) pokers.get(index1);
            Poker poker2 = (Poker) pokers.get(index2);
            pokers.set(index1, poker2);
            pokers.set(index2, poker1);
            
        }
        for(int i = 0 ; i<pokers.size() ; i++){
            System.out.print(pokers.get(i)+"  ");
            //换行
            if(i%10==9){
                System.out.println();
            }
        }
    }
}

结果:

 

posted on 2016-09-28 12:01  小董斌  阅读(216)  评论(0编辑  收藏  举报

导航