A deck of cards, implemented in java

1. Introduction

Pick 4 cards randomly from a deck of 52 cards. All cards can be represented by an array called deck, which is filled with initial values ​​from 0 to S1.
The numbers from 0 to 12, 13 to 25, 26 to 38, and 39 to 51 represent 13 spades, 13 hearts, 13 diamonds, and 13 clubs, respectively. cardNumber/13 determines the suit of the card, and cardNumber%13 decides which card in the specific suit. After scrambling the array deck, select the first four cards from the deck. The program displays the cards corresponding to these four card numbers.

2. Code

package com.zhuo.base.com.zhuo.base;

public class DeckOfcard {
    
    
    public static void main(String[] args) {
    
    
        int [] deck = new int[52];
        String[] suits = {
    
    "Spades", "Hearts", "Diamonds", "Clubs"};
        String[] ranks = {
    
    "Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Gueen", "king"};
        /*初始化*/
        for (int i = 0; i < deck.length; i++)
            deck[i] = i;
        /*洗牌*/
        for (int i = 0; i < deck.length; i++) {
    
    
            int index = (int)(Math.random() * deck.length);
            int temp = deck[i];
            deck[i] = deck[index];
            deck[index] = temp;
        }
        /*显示前四张牌*/
        for (int i = 0; i < 4; i++) {
    
    
            String suit = suits[deck[i] / 13];
            String rank = ranks[deck[i] % 13];
            System.out.println("Cart number" + deck[i] + ": " + rank + " of " + suit);
        }
    }
}

Three. Results display

Cart number35: 10 of Diamonds
Cart number5: 6 of Spades
Cart number38: king of Diamonds
Cart number20: 8 of Hearts

Process finished with exit code 0

Guess you like

Origin blog.csdn.net/weixin_42768634/article/details/113666391