学完集合可以练习一个小题目: 斗地主发牌
package test1; import java.util.ArrayList; import java.util.Collections; //斗地主发牌程式编写 public class TestPoker { public static void main(String[] args) { //三个玩家,起名 Player p1 = new Player("RayLu"); Player p2 = new Player("Bleach"); Player p3 = new Player("Tom"); //整副扑克牌对象创建 Poker poker = new Poker(); //洗牌 poker.pokerShuffle(); //发牌 for(int i = 0; i < poker.getPoker().size(); i++){ if( i % 3 == 0){ p1.getPoker().add(poker.getPoker().get(i)); }else if( i%3==1){ p2.getPoker().add(poker.getPoker().get(i)); }else if(i%3 ==2){ p3.getPoker().add(poker.getPoker().get(i)); } } //发牌完成,遍历每个玩家手中的牌 for(int i = 0; i < p1.getPoker().size(); i++){ System.out.println(p1.getName()+"手中第"+(i+1)+"张牌是:"+p1.getPoker().get(i)); } for(int i = 0; i < p2.getPoker().size(); i++){ System.out.println(p2.getName()+"手中第"+(i+1)+"张牌是:"+p2.getPoker().get(i)); } for(int i = 0; i < p3.getPoker().size(); i++){ System.out.println(p3.getName()+"手中第"+(i+1)+"张牌是:"+p3.getPoker().get(i)); } } } class Poker{ private String[] pokerColor = new String[]{"红桃","黑桃","方片","梅花"}; private String[] pokerNum = new String[]{"A","2","3","4","5","6","7","8","9","10","J","Q","K"}; private ArrayList<String> poker; public Poker(){ poker = new ArrayList<String>(); for(int i =0; i < this.pokerColor.length; i++){ for (int j = 0; j < this.pokerNum.length; j++){ String str = pokerColor[i] + pokerNum[j]; poker.add(str); } } poker.add("大王"); poker.add("小王"); } //获取整副扑克牌 public ArrayList<String> getPoker(){ return poker; } //重洗扑克牌 public void pokerShuffle(){ Collections.shuffle(poker); } } //斗地主玩家 class Player{ private String name;//玩家姓名 private ArrayList<String> poker;//玩家手中的牌 public ArrayList<String> getPoker() { return poker; } public void setPoker(ArrayList<String> poker) { this.poker = poker; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Player(String name) { super(); this.name = name; poker = new ArrayList<String>(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Player other = (Player) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } }