java 实现扑克牌洗牌功能

本博客介绍了一个使用Java实现的扑克牌游戏案例。通过LinkedList存储52张扑克牌,并实现了洗牌功能。博客详细展示了如何创建扑克牌对象、构建牌组及洗牌算法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、使用类

1、LinkList类

  • add(E e) 将指定元素添加到此列表的结尾。

  • get(int index) 返回此列表中指定位置处的元素。

  • size() 返回此列表的元素数。

2、Object类

  • toString() 重写toString使println()方法直接输出对象信息

  • contains(Object o) 如果此列表包含指定元素,则返回 true。

3、Random类

  • nextInt(int n) 返回一个 0(包括)到n(不包括)之间 int 值随机数。

二、代码

import java.util.*;

//需求:使用LinkedList存储一副扑克牌(52张),并且实现洗牌功能

class poker
{
    public poker(String color, String num)
    {
        super();
        this.color = color;
        this.num = num;
    }
    String color;
    String num;

    public String toString()
    {
        return color+num;
    }

}

public class 扑克牌
{
    public static void main(String[] args)
    {
        //生成52张扑克牌
        String[] colors = {"黑桃","方块","梅花","红桃"};
        String[] nums = {"A","2","3","4","5","6","7","8","9","10","J","Q","K"};
        LinkedList pokers = new LinkedList();
        for(int i=0;i < colors.length;i++)
        {
            for(int j=0;j<nums.length;j++)
            {
                pokers.add(new poker(colors[i],nums[j]));
            }
        }
        //洗牌
        LinkedList shuffledpokers = new LinkedList();
        while(shuffledpokers.size()<pokers.size())
        {
            Random x = new Random();
            poker poke = (poker) pokers.get(x.nextInt(pokers.size()));
            if(!shuffledpokers.contains(poke))
            {
                shuffledpokers.add(poke);
            }
        }
        System.out.println("洗牌前:"+pokers);
        System.out.println("洗牌后:"+shuffledpokers);
    }
}

三、截图

这里写图片描述

再次运行:

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值