LinkedList存储一副扑克牌,实现洗牌功能。

package cd.itcast.runble;

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

/**
 * LinkedList存储一副扑克牌,实现洗牌功能。
 * @author 甘兴瑞
 *    2016/11/8
 */
class Poker{
    String huase;
    String num;
    
    public Poker(String huase, String num) {
        this.huase = huase;
        this.num = num;
    }

    @Override
    public String toString() {
        return "{"+huase +num+"}";
    }
    
}

public class Demo2 {
    public static void main(String[] args) {
        LinkedList list2=createPoker();
        xiPoker(list2);//既可以返回linkedList,也可以不反回,使用void,因为共享对象。
        showPoker(list2);
    }
    public static LinkedList createPoker() {
        //存扑克的
                LinkedList list=new LinkedList();
                String[] arr1={"红桃","黑桃","方片","梅花"};
                String[] arr2={"A","2","3","4","5","6","7","8","9","10","J","Q","K"};
                for(int i=0;i<arr1.length;i++){
                    for(int j=0;j<arr2.length;j++){
                        Poker poker=new Poker(arr1[i],arr2[j]);
                        list.add(poker);
                    }
                }
                return list;
    }
    //显示扑克牌
    public static void showPoker(LinkedList pokers) {
        for(int i=0;i<pokers.size();i++){
            System.out.print(pokers.get(i));
            if(i%13==12){
                System.out.println();
            }
        }
    }
    //洗牌的功能
    public static void xiPoker(LinkedList Pokers) {
        //创建随机数对象
        Random ran = new Random();
        for(int i=0;i<100;i++){
            int index1 = ran.nextInt(Pokers.size());
            int index2 = ran.nextInt(Pokers.size());
            Poker poker1 = (Poker)Pokers.get(index1);
            Poker poker2 = (Poker)Pokers.get(index2);
            Pokers.set(index1, poker2);
            Pokers.set(index2, poker1);
        }
    }
}

 

posted on 2016-11-09 14:20  hgfs瑞  阅读(429)  评论(0编辑  收藏  举报

导航