復習Java集合案例_鬥地主

前一段時間生病,趕路,摔跤,受傷......藍瘦的一批.最近20多天一直在復習Java基礎的内容,現在回過頭來看,感覺好多代碼變簡單了,也就感覺沒有必要每天往博客上填代碼了,今天復習到集合,感覺這個鬥地主的案例還比較有意思,上一段代碼走一波.開心一下.代碼如下:

 1 package com.itheima_02;
 2 
 3 import java.util.*;
 4 
 5 /**
 6  * 模擬鬥地主洗牌發牌看牌案例
 7  */
 8 public class Demo07 {
 9     public static void main(String[] args) {
10 //        模擬鬥地主洗牌發牌看牌案例1
11         ddz1();
12 
13     }
14 
15     private static void ddz1() {
16         while (true) {
17             //做牌
18             ArrayList<String> box = new ArrayList<>();
19             String[] kind = {"♠", "♥", "♣", "♦"};
20             String[] num = {"A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"};
21             //裝盒
22             for (String s1 : kind) {
23                 for (String s2 : num) {
24                     box.add(s1 + s2);
25                 }
26             }
27             box.add("joker");
28             box.add("JOKER");
29             //隨機順序洗牌
30             Collections.shuffle(box);
31             //發牌
32             ArrayList<String> player1 = new ArrayList<>();
33             ArrayList<String> player2 = new ArrayList<>();
34             ArrayList<String> player3 = new ArrayList<>();
35             ArrayList<String> bottom = new ArrayList<>();
36             for (int i = 0; i < box.size(); i++) {
37                 String pres = box.get(i);
38                 if (i >= box.size() - 3) {
39                     bottom.add(pres);
40                 } else if (i % 3 == 0) {
41                     player1.add(pres);
42                 } else if (i % 3 == 1) {
43                     player2.add(pres);
44                 } else if (i % 3 == 2) {
45                     player3.add(pres);
46                 }
47             }
48             //看牌
49             check("玩家1", player1);
50             check("玩家2", player2);
51             check("玩家3", player3);
52             check("底", bottom);
53             System.out.println("輸入exit退出,輸入re重發");
54             Scanner sc = new Scanner(System.in);
55             String s = sc.nextLine();
56             if (s.equals("exit")) {
57                 System.exit(0);
58             } else if (s.equals("re")) {
59                 continue;
60             }
61         }
62     }
63 
64     private static void check(String name, ArrayList<String> box) {
65         System.out.println(name + "牌是:");
66         for (String pres : box) {
67             System.out.print(pres + " ");
68         }
69         System.out.println("
");
70     }
71 }

這裏用一個while循環包裹了代碼,運行后程序需要在控制臺輸入exit結束,或者輸入re,程序重新執行.

原文地址:https://www.cnblogs.com/zzzzzpaul/p/11370034.html