欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

编写一个发牌程序(Java语言描述)

程序员文章站 2022-07-14 23:18:12
...
import java.util.Random;

public class Cards {
    
    /**
     * 初始化标志数组,牌均未发出
     */
    private int[][] cards = new int[4][13];
    
    /**
     * 花色
     */
    private String[] suits;
    
    /**
     * 点数
     */
    private String[] points;

    /**
     * 构造器初始化花色、点数
     * @param suits
     * @param points
     */
    public Cards(String[] suits, String[] points) {
        super();
        this.suits = suits;
        this.points = points;
    }

    public int[][] getCards() {
        return cards;
    }

    public void setCards(int[][] cards) {
        this.cards = cards;
    }

    public String[] getSuits() {
        return suits;
    }

    public void setSuits(String[] suits) {
        this.suits = suits;
    }

    public String[] getPoints() {
        return points;
    }

    public void setPoints(String[] points) {
        this.points = points;
    }

    public void sendCards(int n) {
        //记录扑克牌信息
        String sendCards = new String("发放的扑克牌为:");
        //生成随机数的生成对象
        Random randomBuilder = new Random();
        //定义发放扑克牌花色、点数
        int suit, point;
        for (int i = 0; i < n; ) {
            suit = randomBuilder.nextInt(4);
            point = randomBuilder.nextInt(13);
            if (cards[suit][point] == 1) {
                continue;
            } else {
                cards[suit][point] = 1;
                //追加新发扑克牌花色
                sendCards = sendCards + suits[suit];
                //追加点数
                sendCards = sendCards + points[point] + " ";
                //准备发放下一张牌
                i++;
            }
        }
        System.out.println(sendCards.toString());
    }
    
    public static void main(String[] args) {
        String[] suits = {"红心", "方片", "梅花", "黑桃"};
        String[] points = {"A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"};
        Cards cards = new Cards(suits, points);
        cards.sendCards(10);
    }
    
}

运行程序,发现在0<=x<=52范围内可以得到随机发牌的准确结果。
提供代码的main方法里是发10张牌,运行示例:

发放的扑克牌为:黑桃8 方片J 红心3 黑桃J 黑桃10 方片10 红心7 黑桃A 黑桃Q 红心A