java生成撲克牌----java基礎學習總結


前言都懶的寫了,都凌晨1點半了,直接把代碼放上去

代碼:

 1 package com.day16.list;
 2 
 3 import java.util.LinkedList;
 4 import java.util.Random;
 5 
 6 /**
 7  * 類說明 :
 8  * 
 9  * @author 作者 : chenyanlong
10  * @version 創建時間:2017年10月29日
11  */
12 
13 // 撲克類
14 class Poker {
15 
16     String color;// 花色
17     String num;// 點數
18 
19     // 構造方法
20     public Poker(String color, String num) {
21         super();
22         this.color = color;
23         this.num = num;
24     }
25 
26     // 重寫toString()
27     @Override
28     public String toString() {
29         return color+num;
30     }
31 
32 }
33 
34 public class Demo {
35     
36     public static void main(String[] args) {
37         //實例化集合對象
38         LinkedList pockers=createPoker();
39         flushPockes(pockers);//洗牌
40         showPoker(pockers);//顯示多少張牌
41         
42     }
43     
44     //生成撲克牌的方法
45     public  static LinkedList createPoker(){
46         //該集合用於存儲撲克對象
47         LinkedList list=new LinkedList();
48         //定義數組存儲所有的花色和點數
49         String[] colors={"黑色","紅桃","梅花","方塊"};
50         String[] nums={"A","2","3","4","5","6","7","8","9","10","J","Q","K"};
51         
52         //添加集合中撲克牌
53         for(int i=0;i<nums.length;i++){
54             for(int j=0;j<colors.length;j++){
55                 list.add(new Poker(colors[j],nums[i]));
56             }
57         }
58         return list;
59     }
60     
61     //洗牌的功能
62     public static void flushPockes(LinkedList pockers){
63        //創建隨機對象
64         Random random=new Random();
65         for(int i=0;i<100;i++){
66             //隨機產生兩個索引值
67             int a=random.nextInt(pockers.size());
68             int b=random.nextInt(pockers.size());
69             //根據索引值取出兩張牌
70             Poker a1= (Poker) pockers.get(a);
71             Poker b1= (Poker) pockers.get(b);
72             pockers.set(a, b1);
73             pockers.set(b, a1);
74         }
75     }
76     
77     //顯示撲克牌
78     public static void showPoker(LinkedList pockers){
79         for(int i=0;i<pockers.size();i++){
80             System.out.print("  "+pockers.get(i));         
81             //換行
82             if(i%10==9){
83                 System.out.println();
84             }
85         }
86         System.out.println();
87         System.out.println("牌數:"+pockers.size());//顯示多少張牌
88     }
89     
90 }

 

運行效果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM