Main方法:
public static void main(String[] args) {
//利用字典, 1-54 大王....♠3
Map<Integer,String> poker = new HashMap<>();
//添加 第一张牌大王,第二张牌小王
int index = 0;
poker.put(++index,"大王");
poker.put(++index,"小王");
//创建花色
ArrayList<String> colors = new ArrayList<>();
//创建数字
ArrayList<String> numbers = new ArrayList<>();
Collections.addAll(colors, "♦", "♣", "♥", "♠");
Collections.addAll(numbers,"2","A","K","Q","J","10","9","8","7","6","5","4","3");
//组合花色
//因为花色之间相差1,所以color的循环在里面
for (String number : numbers)
for (String color : colors)
//因为玩牌习惯叫 ?花 几
poker.put(++index,color+number);
ArrayList<Integer> pokerIndex = new ArrayList<>();
//使用addAll实现 List-Set的转换
pokerIndex.addAll(poker.keySet());
//洗牌就是打乱索引
Collections.shuffle(pokerIndex);
ArrayList<Integer> player1 = new ArrayList<>();
ArrayList<Integer> player2 = new ArrayList<>();
ArrayList<Integer> player3 = new ArrayList<>();
ArrayList<Integer> dipai = new ArrayList<>();
//发牌
for (int i = 0; i < pokerIndex.size(); i++) {
if(i<=2)
dipai.add(pokerIndex.get(i));
else{
if(i%3==1)
player1.add(pokerIndex.get(i));
if(i%3==2)
player2.add(pokerIndex.get(i));
if(i%3==0)
player3.add(pokerIndex.get(i));
}
}
//Collections工具类的排序方法
Collections.sort(player1);
Collections.sort(player2);
Collections.sort(player3);
Collections.sort(dipai);
//读牌方法
printPai(poker, player1,"张三");
printPai(poker, player2,"李四");
printPai(poker, player3,"王五");
}
private static void printPai(Map<Integer, String> poker, ArrayList<Integer> player,String playName) {
StringBuffer stringBuffer = new StringBuffer();
//输出玩家姓名
stringBuffer.append(playName+": [");
for (Integer playerIndex : player) {
//每一张牌用","分割
stringBuffer.append(poker.get(playerIndex)).append(",");
}
//获取最后一个 ”,“索引
int i = stringBuffer.lastIndexOf(",");
//替换”,“->"]" (开始位置-包含 ,结束位置-不包含) 所以从i开始,往后查一位。
stringBuffer.replace(i,i+1,"]");
// String substring = stringBuffer.substring(0, i);
System.out.println(stringBuffer);
}
输出结果:
张三: [大王,♦2,♠A,♣K,♥K,♠K,♦Q,♦J,♦10,♣9,♦7,♣7,♠6,♣5,♦3,♥3,♠3]
李四: [小王,♠2,♦A,♥J,♠J,♣10,♥9,♠9,♣8,♥8,♠8,♠7,♦6,♣6,♥6,♥5,♠4]
王五: [♣2,♣A,♥A,♥Q,♠Q,♣J,♥10,♠10,♦9,♦8,♥7,♦5,♠5,♦4,♣4,♥4,♣3]
Process finished with exit code 0
总结:
利用<K,V>生成牌的字典。使用Map中的entrySet()获得单列结合Set(里面存放的是牌的索引),使用Collection中的addAll将Set集合转换成List集合,使用Collection中的AddAll,一次向集合中添加多个元素,使用Collection的sort对牌进行排序。使用StringBuffer中的Append与subString对字符串进行增减,使用lastIndexOf获取索引位置,使用replace进行字符串的替换。