java20240101

文章介绍了如何使用Java的HashMap数据结构统计字符串中字符的出现次数,以及如何组织和洗牌斗地主牌组的过程。
摘要由CSDN通过智能技术生成

1.利用map统计字符串中 字符出现的次数

System.out.println("请输出一段英文:");
//从键盘获取
Scanner scanner = new Scanner(System.in);
String line = scanner.nextLine();
//创建集合
HashMap<Character, Integer> map = new HashMap<>();
//循环
for (int i = 0; i < line.length();i++) {
    char key = line.charAt(i);//获取字符
    Integer count = map.get(key);//获取map里 键key 的值  并赋给 count(出现的次数)
    if (null == count){//如果是空 就记为出现一次
        map.put(key,1);
    }else {//如果不是空 就加一次
        map.put(key,++count);
    }
}

Set<Character> characters = map.keySet();//获取键的集合
for (Character key : characters) {
    System.out.println(key + ":" + map.get(key) + "个");
}

2.斗地主

        HashMap<Integer, String> card = new HashMap<>();//扑克牌
        ArrayList<Integer> indexList = new ArrayList<>();//索引

        String[] colors = {"♥","♠","♦","♣"};
        String[] nums = {"3","4","5","6","7","8","9","10","J","Q","K","A","2"};

        //将花色和点数 组织好 放到扑克牌里
        int index = 0;
        for (String num : nums){
            for (String color : colors){
                card.put(index,color+num);//组装扑克牌
                indexList.add(index++);//索引
            }
        }
        //大小王单独处理
        card.put(index,"¥");
        indexList.add(index);
        card.put(++index,"$");
        indexList.add(index);

        //洗牌
        Collections.shuffle(indexList);

        //定义玩家
        TreeSet<Integer> p1 = new TreeSet<>();
        TreeSet<Integer> p2 = new TreeSet<>();
        TreeSet<Integer> p3 = new TreeSet<>();
        //底牌
        TreeSet<Integer> lastCard = new TreeSet<>();

        //发牌
        for (int i = 0; i < indexList.size(); i++) {
            if ( i >= indexList.size()-3 ){
                lastCard.add(indexList.get(i));
            }else {
                switch ( i % 3 ){
                    case 0:
                        p1.add(indexList.get(i));
                        break;
                    case 1:
                        p2.add(indexList.get(i));
                        break;
                    case 2:
                        p3.add(indexList.get(i));
                        break;
                }
            }
        }

        //看牌
        showCard("涅尘",p1,card);
        showCard("美娜",p2,card);
        showCard("科比",p3,card);
        showCard("底牌",lastCard,card);
    }

    private static void showCard(String name, TreeSet<Integer> type, HashMap<Integer, String> card) {
        System.out.print(name + ":");

        for (Integer index : type){
            System.out.print(card.get(index)+" ");
        }

        System.out.println("\n");

  • 11
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值