zoukankan      html  css  js  c++  java
  • 使用LinkedList模拟洗牌功能

    package cn.itcast.collection;
    
    import java.util.LinkedList;
    import java.util.Random;
    
    /*使用LinkedList模拟洗牌功能*/
    
    //扑克牌类
    class Poker {
        String color;// 花色
        String num;// 点数
    
        public Poker(String color, String num) {
            this.color = color;
            this.num = num;
        }
    
        @Override
        public String toString() {
            return "{" + color + num + "}";
        }
    
    }
    
    public class Demo3 {
    
        public static void main(String[] args) {
            LinkedList poker = createPoker();
            shufflePoker(poker);
            showPoker(poker);
    
        }
    
        // 洗牌功能
        public static void shufflePoker(LinkedList poker) {
            // 创建随机数
            Random random = new Random();
            for (int i = 0; i < 100; i++) {
                // 随机产生2个索引值,并交换两张牌的顺序
                int index1 = random.nextInt(poker.size());
                int index2 = random.nextInt(poker.size());
    
                Poker poker1 = (Poker) poker.get(index1);
                Poker poker2 = (Poker) poker.get(index2);
                poker.set(index1, poker2);
                poker.set(index2, poker1);
            }
        }
    
        // 生产扑克牌
        public static LinkedList createPoker() {
            String[] strColor = new String[] { "黑桃", "红桃", "梅花", "方块" };
            String[] strNum = new String[] { "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K" };
            LinkedList list = new LinkedList();
            for (int i = 0; i < strColor.length; i++) {
                for (int j = 0; j < strNum.length; j++) {
                    list.add(new Poker(strColor[i], strNum[j]));
                }
            }
            return list;
        }
    
        // 显示扑克牌
        public static void showPoker(LinkedList list) {
            for (int i = 0; i < list.size(); i++) {
                System.out.print(list.get(i));
                if (i % 10 == 9) {
                    System.out.println();
                }
            }
        }
    
    }
  • 相关阅读:
    java8特性 Optional 工具类
    SpringBoot 配置支付宝接口
    Redis宕机 快速恢复
    flowable流程引擎通过模型ID部署流程
    java OA系统 自定义表单 流程审批 电子印章 手写文字识别 电子签名 即时通讯
    Mybatis 动态执行SQL语句
    idea 访问 jsp 404问题
    变量名的命名
    CSS设计 Search窗口
    jQuery实现Ajax功能示例
  • 原文地址:https://www.cnblogs.com/running-fish/p/9511433.html
Copyright © 2011-2022 走看看