import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class practice01 {
public static void main(String[] args) {
//封装扑克牌,四种花色
String[] colors={"?","?","?","?"};
String[] nums={"3","4","5","6","7","8","9","10","J","Q","K","A","2"};
//定义一个Map来装扑克牌,键是用来存储54张扑克牌对应的序号,值就是扑克牌的牌面
Map<Integer,String> pokerMap=new HashMap<>();
//来装扑克牌的54个序号
List<Integer> indexList=new ArrayList<>();
int index=1;
//用的是数字排序,所以必须把nums放在外层;如果用花色排序,则把colors放在外层
for (String n : nums) {
for(String c:colors){
pokerMap.put(index, c+n);
indexList.add(index);
index++;
}
}
//封装大小王,上一步完成之后,index=53
pokerMap.put(index, "小王");
indexList.add(index);
index++;
pokerMap.put(index, "大王");
indexList.add(index);
//洗扑克牌,集合工具类的方法
Collections.shuffle(indexList);
//发牌,用数组来装序号的数字,序号大于51的三张扑克牌作为底牌
List<Integer> user1=new ArrayList<>();
List<Integer> user2=new ArrayList<>();
List<Integer> user3=new ArrayList<>();
List<Integer> dipai=new ArrayList<>();
//根据取模3的余数来分配给玩家对应的扑克牌
for (int i = 0; i < indexList.size(); i++) {
if(i>=indexList.size()-3){
dipai.add(indexList.get(i));
}else if(i % 3==0){
user1.add(indexList.get(i));
}else if(i % 3==1){
user2.add(indexList.get(i));
}else if(i % 3==2){
user3.add(indexList.get(i));
}
}
//排序,每个玩家的扑克牌分别排序
Collections.sort(user1);
Collections.sort(user2);
Collections.sort(user3);
Collections.sort(dipai);
//看牌,用户的序号作为map的键找出与之对应的值
System.out.println("卡特的牌:");
printSee(pokerMap,user1);
System.out.println("盖伦的牌:");
printSee(pokerMap,user2);
System.out.println("剑圣的牌:");
printSee(pokerMap,user3);
System.out.println("底牌牌:");
printSee(pokerMap,dipai);
}
//写一个方法来看牌,降低代码的冗余性
private static void printSee(Map<Integer, String> map, List<Integer> user) {
//创建字符串容器,拼接每个玩家的扑克牌
StringBuilder bul=new StringBuilder("[");
for(int i=0;i<user.size();i++){
if(i<user.size()-1){
bul.append(map.get(user.get(i))).append(",");
}else{
bul.append(map.get(user.get(i))).append("]");
}
}
//转换成字符串方式
System.out.println(bul.toString());
}
}
原文地址:https://www.cnblogs.com/horse123/p/8535368.html