集合综合案例
案例介紹
斗地主綜合案例:
? ? ? ? 1.準備牌
? ? ? ? 2.洗牌
? ? ? ? 3.發牌
? ? ? ? 4.看牌
package com.itheima.demo04.Test;import java.util.ArrayList;
import java.util.Collections;public class DouDiZhu {public static void main(String[] args) {//1.準備牌//定義一個存儲54張牌的ArrayList集合,泛型使用StringArrayList<String> poker = new ArrayList<>();//定義兩個數組,一個數組存儲牌的花色,一個數組存儲牌的序號String[] colors = {"?","?","?","?"};String[] numbers = {"2","A","K","Q","J","10","9","8","7","6","5","4","3"};//先把大王和小王存儲到poker集合中poker.add("大王");poker.add("小王");//循環嵌套遍歷兩個數組,組裝52張牌for(String number : numbers){for (String color : colors) {//System.out.println(color+number);//把組裝好的牌存儲到poker集合中poker.add(color+number);}}//System.out.println(poker);/*2.洗牌使用集合的工具類Collections中的方法static void shuffle(List<?> list) 使用默認隨機源對指定列表進行置換。*/Collections.shuffle(poker);//System.out.println(poker);/*3.發牌*///定義4個集合,存儲玩家的牌和底牌ArrayList<String> player01 = new ArrayList<>();ArrayList<String> player02 = new ArrayList<>();ArrayList<String> player03 = new ArrayList<>();ArrayList<String> diPai = new ArrayList<>();/*遍歷poker集合,獲取每一張牌使用poker集合的索引%3給3個玩家輪流發牌剩余3張牌給底牌注意:先判斷底牌(i>=51),否則牌就發沒了*/for (int i = 0; i < poker.size() ; i++) {//獲取每一張牌String p = poker.get(i);//輪流發牌if(i>=51){//給底牌發牌diPai.add(p);}else if(i%3==0){//給玩家1發牌player01.add(p);}else if(i%3==1){//給玩家2發牌player02.add(p);}else if(i%3==2){//給玩家3發牌player03.add(p);}}//4.看牌System.out.println("劉德華:"+player01);System.out.println("周潤發:"+player02);System.out.println("周星馳:"+player03);System.out.println("底牌:"+diPai);}
}
?
總結
- 上一篇: 数组 ——求出一组数的最大值(用数组
- 下一篇: 常见的数据结构——栈、队列、数组、链表和