String faces = pokerBox.get(i);
if (i>=51) {
diPai.add(faces);
} else if (i%3==0) {
player01.add(faces);
} else if (i%3==1) {
player02.add(faces);
} else if (i%3==2) {
player03.add(faces);
}
}
/**
* 四、看牌
直接输出每位玩家的集合
*/
System.out.println("张无忌"+player01);
System.out.println("张翠山"+player02);
System.out.println("殷素素"+player03);
System.out.println("底牌"+diPai);
}
}
带排序版的
package com.demo_2.poker;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
public class Poker {
/**
*一共要四步。一、备牌 二、洗牌 三、发牌 四、看牌
目的:练习集合的用法
*/
public static void main(String[] args) {
/**
* 第一步:备牌
使用List接口中的of()方法添加并分别创建numbers和colors集合
*/
//numbers:存储普通牌 2、A、K...3从大到小
List numbers = List.of("2", "A", "K", "Q", "J", "10", "9", "8", "7", "6", "5", "4", "3");
//colors:存储四种花色 ♥、♠、♦、♣
List colors = List.of("♥", "♠", "♦", "♣");
//创建一个Map集合存储索引和组装好的牌
HashMap pokerBox &#61; new HashMap<>();
//创建一个List集合储存牌的索引
LinkedList pokerIndex &#61; new LinkedList<>();
//先把大王、小王和下标分别放进Map的键和值里面,再向LinkedList里面存储下标&#xff0c;下标增加1
int index &#61; 0;
pokerBox.put(index, "大王");
pokerIndex.add(index);
index&#43;&#43;;
pokerBox.put(index, "小王");
pokerIndex.add(index);
index&#43;&#43;;
//组装牌&#xff1a;遍历两个List集合&#xff0c;使用Map接口中的put()方法给pokerBox添加键和值&#xff0c;并给LinkedList传下标
for (String number : numbers) {
for (String color : colors) {
pokerBox.put(index, color &#43; number);
pokerIndex.add(index);
index&#43;&#43;;
}
}
/**
* 第二步&#xff1a;洗牌
使用Collocations类中的shuffler方法&#xff0c;传递参数pokerIndex
*/
Collections.shuffle(pokerIndex);
/**
* 第三步&#xff1a;发牌
创建四个List集合&#xff0c;分别存储三位玩家和底牌
使用for循环遍历pokerIndex&#xff0c;i%3结果为0的给玩家1&#xff0c;1的给玩家2&#xff0c;2的给玩家3
*/
LinkedList player01 &#61; new LinkedList<>();
LinkedList player02 &#61; new LinkedList<>();
LinkedList player03 &#61; new LinkedList<>();
LinkedList diPai &#61; new LinkedList<>();
for (int i &#61; 0; i Integer in &#61; pokerIndex.get(i);
if (i >&#61; 51) {
diPai.add(in);
} else if (i % 3 &#61;&#61; 0) {
player01.add(in);
} else if (i % 3 &#61;&#61; 1) {
player02.add(in);
} else if (i % 3 &#61;&#61; 2) {
player03.add(in);
}
}
//给玩家的牌排序&#xff0c;使用Collocations接口中的sort()方法排序
Collections.sort(player01);
Collections.sort(player02);
Collections.sort(player03);
Collections.sort(diPai);
/**
*第四步&#xff1a;看牌
遍历排过序的List集合作为Map集合的键值获取对应的值
为提高代码复用性定义一个方法代替
*/
print("令狐冲",player01,pokerBox);
print("诸葛瑾",player02,pokerBox);
print("司马懿",player03,pokerBox);
print("底牌",diPai,pokerBox);
}
/**
*看牌的方法&#xff1a;
参数&#xff1a;
String name
LinkedList list
HashMap map
*/
public static void print(String name,LinkedList list,HashMap map){
System.out.print(name&#43;"&#xff1a;");
for (Integer key : list) {
System.out.print(map.get(key)&#43;" ");
}
System.out.println();
}
}
以上就是本文的全部内容&#xff0c;希望对大家的学习有所帮助&#xff0c;也希望大家多多支持聚米学院。