使用LinkedList存储一副扑克牌(除开大小王),实现洗牌功能。

package com;
import java.util.*;
/*
 * 使用LinkedList存储一副扑克牌(除开大小王),实现洗牌功能。
 * */
public class Homework3 {
public static void main(String[] args) {
//生成一副扑克牌
LinkedList pokers=storagePoker();
//洗牌
shufflePoker(pokers);
//显示洗牌后的扑克牌
showPoker(pokers);
System.out.println("扑克牌的张数为:"+pokers.size());
}
//生成扑克牌的方法
public static LinkedList storagePoker(){
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;ifor(int j=0;j//将每张扑克牌对象添加到集合中
list.add(new Poker(colors[i],nums[j]));
}
}
return list;
}
//洗牌的方法
public static void shufflePoker(LinkedList poker){
Random random=new Random();
for(int i=0;i<1000;i++){
int index1=random.nextInt(52);//从 牌的集合中 获取一张牌0 - 51 之间的随机数
int index2=random.nextInt(52);//从 牌的集合中 获取一张牌0 - 51 之间的随机数
//拿到两张随机的牌
Poker poker1=(Poker)poker.get(index1);
Poker poker2=(Poker)poker.get(index2);
//交换两张牌位置
poker.set(index1, poker2);
poker.set(index2, poker1);
}
}
//显示洗好的扑克牌
public static void showPoker(LinkedList poker){
for(int i=0;iSystem.out.println(poker.get(i));
}
}
}
class Poker {
String color;//花色
String num;//数字
public Poker(String color,String num){
this.color=color;
this.num=num;
}
//重写toString方法
public String toString(){
return "{"+color+num+"}";
}
}

你可能感兴趣的:(使用LinkedList存储一副扑克牌(除开大小王),实现洗牌功能。)