首页 > 代码库 > java随机发牌

java随机发牌

public class CardGame{    public static void main(String[] args) {        String[]suits={"spades","dimonds","Hearts","clubs"};        String[]nums={"A","2","3","4","5","6","7","8","9","10","J","Q","K"};        // 52张牌        int []cards=new int[52];        for(int i=0;i<cards.length;i++)        {            cards[i]=i;        }        // 洗牌,打乱顺序        int temp;        for (int i=0;i<cards.length ;i++ ) {            int index=(int)(Math.random()*cards.length);            temp=cards[index];            cards[index]=cards[i];            cards[i]=temp;//cards数组此时已经不是从0到51顺序排列的了        }        // 发牌        for (int i=0;i<cards.length ;i++ ) {            String cardNum=nums[cards[i]%13];            String suit=suits[cards[i]/13];            System.out.println("第"+(i+1)+"张牌是:"+suit+cardNum);        }        /*        *主要思路:        *1.为了保证52张牌每张都不重复        *    牌的花色有4种,每种花色循环13次>>>>0到51的整数除以13,得到的商为0到4(0-12:0;13-25:1···)        *    牌的数字有13种,每个数字出现4次>>>>0到51的整数除以13,取模的值为0到13.从0到12循环四次。        *2.为了保证随机性        *    创建了cards[]数组,为其元素赋值0到51,然后打乱元素的顺序        */    }}