利用Java的ArrayList实现随机给三个人发扑克牌
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
class Card{
private int rank;
private String suit;
public Card(int rank, String suit) {
this.rank = rank;
this.suit = suit;
}
@Override
public String toString() {
return "[ " + this.suit +" : "+this.rank + " ]";
}
}
public class TestDemo {
private static final String[] suits = {"♥","♠","♣","♦"};
public static List<Card> buyCard() {
ArrayList<Card> cards= new ArrayList<>();
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 13; j++) {
cards.add(new Card(j,suits[i]));
}
}
return cards;
}
private static void swap(List<Card> cards ,int i ,int j){
Card tmp = cards.get(i);
cards.set(i,cards.get(j));
cards.set(j,tmp);
}
public static void shuffle(List<Card> cards){
int size = cards.size();
for (int i = size - 1; i > 0; i--) {
Random random = new Random();
int rand = random.nextInt(i);
swap(cards,i,rand);
}
}
public static void main(String[] args) {
List<Card> cards = buyCard();
shuffle(cards);
//System.out.println(cards);
ArrayList<List<Card>> hand = new ArrayList<>();
ArrayList<Card> hand1 = new ArrayList<>();
ArrayList<Card> hand2 = new ArrayList<>();
ArrayList<Card> hand3 = new ArrayList<>();
hand.add(hand1);
hand.add(hand2);
hand.add(hand3);
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 3; j++) {
Card card = cards.remove(0);
hand.get(j).add(card);
}
}
System.out.println("the first people's cards :" + hand1);
System.out.println("the second people's cards :" + hand2);
System.out.println("the third people's cards :" + hand3);
System.out.println("the rest cards :" + cards);
}
}