java 實現撲克牌洗牌功能

一、使用類

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);
    }
}

三、截圖

這裏寫圖片描述

再次運行:

這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章