利用LinkedList生成一副扑克牌

 import java.util.LinkedList;
import java.util.Random; //自定义一个Poker类,用于存储扑克的信息(花色、数字)
class Poker{
String color;
String numbers; public Poker(String color, String numbers) {
this.color = color;
this.numbers = numbers;
} //重写toString方法
@Override
public String toString() {
return color + numbers;
} } public class Demo3 {
public static void main(String[] args) {
LinkedList pokers = CreatePoker();
shufflePoker(pokers);
showPoker(pokers);
} //生成一副扑克牌
public static LinkedList CreatePoker(){
LinkedList list = new LinkedList();
String[] color = {"红桃","黑桃","梅花","方块"};
String[] numbers = {"A","2","3","4","5","6","7","8","9","10","J","Q","K"};
for (int i = 0; i < numbers.length; i++) {
for (int j = 0; j < color.length; j++) {
list.add(new Poker(color[j], numbers[i]));
}
}
return list;
} //将扑克牌信息打印
public static void showPoker(LinkedList pokers){
for (int i = 0; i < pokers.size(); i++) {
System.out.print(pokers.get(i) + " ");
//为什么等于9?因为等于0的话,i为0时,直接换行打印。等于9是0 ~ 9,就是每十张牌变换行一次
if(i % 10 == 9){
System.out.println();
}
}
} //洗牌
public static void shufflePoker(LinkedList pokers){
Random random = new Random();
for (int i = 0; i < 100; i++) { //i < 10也行,只不过原则上越大,牌洗得越乱
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);
}
}
}
上一篇:了解Solr6.1结构及实现原理


下一篇:np.tile 函数使用