利用LinkedList生成一副扑克牌

本文介绍了一个使用Java实现的扑克牌生成器,并演示了如何创建一副标准的扑克牌及进行洗牌的过程。通过自定义Poker类来存储花色和数字信息,并利用LinkedList进行牌组管理。
 1 import java.util.LinkedList;
 2 import java.util.Random;
 3 
 4 //自定义一个Poker类,用于存储扑克的信息(花色、数字)
 5 class Poker{
 6     String color;
 7     String numbers;
 8     
 9     public Poker(String color, String numbers) {
10         this.color = color;
11         this.numbers = numbers;
12     }
13     
14     //重写toString方法
15     @Override
16     public String toString() {
17         return color + numbers;
18     }
19         
20 }
21 
22 
23 public class Demo3 {
24     public static void main(String[] args) {
25         LinkedList pokers = CreatePoker();
26         shufflePoker(pokers);
27         showPoker(pokers);
28     }
29     
30     //生成一副扑克牌
31     public static LinkedList CreatePoker(){
32         LinkedList list = new LinkedList();
33         String[] color = {"红桃","黑桃","梅花","方块"};
34         String[] numbers = {"A","2","3","4","5","6","7","8","9","10","J","Q","K"};
35         for (int i = 0; i < numbers.length; i++) {
36             for (int j = 0; j < color.length; j++) {
37                 list.add(new Poker(color[j], numbers[i]));
38             }
39         }
40         return list;
41     }
42     
43     //将扑克牌信息打印
44     public static void showPoker(LinkedList pokers){
45         for (int i = 0; i < pokers.size(); i++) {
46             System.out.print(pokers.get(i) + " ");
47             //为什么等于9?因为等于0的话,i为0时,直接换行打印。等于9是0 ~ 9,就是每十张牌变换行一次
48             if(i % 10 == 9){
49                 System.out.println();
50             }
51         }
52     }
53     
54     //洗牌
55     public static void shufflePoker(LinkedList pokers){
56         Random random = new Random();
57         for (int i = 0; i < 100; i++) { //i < 10也行,只不过原则上越大,牌洗得越乱
58             int index1 = random.nextInt(pokers.size());
59             int index2 = random.nextInt(pokers.size());
60             Poker poker1 = (Poker) pokers.get(index1); 
61             Poker poker2 = (Poker) pokers.get(index2);
62             pokers.set(index1, poker2);
63             pokers.set(index2, poker1);
64         }
65     }
66 }

 

转载于:https://www.cnblogs.com/shadowdoor/p/6810014.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值