Introduction to Java - static code block case

Case: Fight the Landlords game

  • When starting the game room, 54 cards should be prepared in advance, and these card data can be used directly later.

 

import java.util.ArrayList;
public class StaticDemo {
    /**
     * 1.定义一个静态的集合,这样这个集合只加载一个,因为当前房间只有一副牌
     */
    public static ArrayList<String> cards = new ArrayList<>();

    /**
     * 2.在流程正真执行main方法前,把54张牌放进去吧,后续游戏可以直接使用了
     */
    static {
        //3.正式做牌,放到集合中去
        //定义一个数组存储全部点数,类型确定,个数确定
        String[] sizes = {"A","2","3","4","5","6","7","8","9","10","J","Q","K"};
        //定义一个数组存储全部花色,类型确定,个数确定
        String[] colors = {"♤","♡","♢","♧"};
        //遍历点数
        for (int i = 0; i < sizes.length; i++) {
            //遍历花色
            for (int j = 0; j < colors.length; j++) {
                String card = sizes[i] + colors[j];
                cards.add(card);
            }
        }
        //单独加入大小王
        cards.add("小王");
        cards.add("大王");
    }
    
    public static void main(String[] args) {
        //目标:模拟游戏启动前,初始化54张牌数据
        System.out.println("新牌:" + cards);
    }
}

Guess you like

Origin blog.csdn.net/weixin_61275790/article/details/129798757