第一步:我们要先创建一个Card对象
解释说明:size为扑克牌里的数字,color为花色
public class Card {
private String size;
private String color;
public Card() {
}
public Card(String size, String color) {
this.size = size;
this.color = color;
}
public String getSize() {
return size;
}
public void setSize(String size) {
this.size = size;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
@Override
public String toString() {
return color+size;
}
}
第二步:我们要创建一个List集合来存储Card对象。
第三步:通过循环把数据存进list集合。
第四步: Collections工具类里的shuffle方法来打乱list集合里的数据。
第五步:再创建三个list集合,通过循环把数据分别数据存进这三个数据,把最后三张牌作为地主牌。
public static String[] colors = {"♠", "♣", "♥", "◆"};
public static String[] huaPai = {"J", "Q", "K", "大王", "小王"};
public static List<Card> cards = new ArrayList<>();
static {
//初始化扑克牌
for (int i = 1; i <= 10; i++) {
for (int j = 0; j < colors.length; j++) {
Card card = new Card(String.valueOf(i), colors[j]);
cards.add(card);
}
}
for (int i = 0; i < huaPai.length; i++) {
for (int j = 0; j < colors.length; j++) {
if (i > 2) {
Card card = new Card(huaPai[i], "");
cards.add(card);
break;
}
Card card = new Card(huaPai[i], colors[j]);
cards.add(card);
}
}
System.out.println("洗牌前");
for (Card card : cards) {
System.out.print(card);
}
System.out.println();
}
public static void main(String[] args) {
// System.out.println("洗牌后");
Collections.shuffle(cards);
// for (Card card : cards) {
// System.out.print(card);
// }
List<Card> xiaomi = new ArrayList<>();
List<Card> xiaoho = new ArrayList<>();
List<Card> xiaotan = new ArrayList<>();
List<Card> san = new ArrayList<>();
for (int i = 0; i < cards.size(); i++) {
if (i >= cards.size() - 3) {
Card card = cards.get(i);
san.add(card);
continue;
}
if (i % 3 == 1) {
Card card = cards.get(i);
xiaomi.add(card);
}
if (i % 3 == 2) {
Card card = cards.get(i);
xiaoho.add(card);
}
if (i % 3 == 0) {
Card card = cards.get(i);
xiaotan.add(card);
}
}
System.out.println();
System.out.println("小红的的牌:");
for (Card card : xiaoho) {
System.out.print(card);
}
// System.out.println(xiaoho.size());
System.out.println();
System.out.println("小米的牌:");
for (Card card : xiaomi) {
System.out.print(card);
}
// System.out.println(xiaomi.size());
System.out.println();
System.out.println("小谭的牌:");
for (Card card : xiaotan) {
System.out.print(card);
}
// System.out.println(xiaotan.size());
System.out.println();
System.out.println("地主牌:");
for (Card card : san) {
System.out.print(card);
}
}
}