利用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 }

 

posted @ 2017-05-04 21:38  shadowdoor  阅读(319)  评论(0编辑  收藏  举报