抽牌问题,一副牌一直抽取直至不够抽取。
注意问题:random产生的随机数是可重复的,所以每抽一次牌,都要从pk中去除一次。
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//获取了一副完整的扑克牌pk
ArrayList<String> pk = proPK();
System.out.println("现在有一副完整的牌,请输入需要抽取的张数:");
//开始抽牌
while(true){
int n = sc.nextInt();
if(n>pk.size()){
System.out.println("已经没有这么多牌可以抽啦");
break;
}
//获取抽取的牌的集合draw
ArrayList<String> draw = draw(n,pk);
ArrayList<String> pk1 = quChong(pk, draw);
System.out.println("还剩"+pk1.size()+"张牌"+pk);
System.out.println("抽取了"+draw.size()+"张牌"+draw);
}
}
//随机抽取的n张牌
public static ArrayList<String> draw(int n,ArrayList<String> list){
ArrayList<String> list1 = new ArrayList<>();
Random r = new Random();
for (int i = 0; i < n; i++) {
int num = r.nextInt(list.size());
list1.add(list.get(num));
list.remove(num);
}
return list1;
}
//获得一副完整的扑克牌
public static ArrayList<String> proPK(){
ArrayList<String> list = new ArrayList<>();
String[] hs = {"黑桃", "红桃", "梅花", "方片"};
String[] ds = {"A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"};
for (int i = 0; i < hs.length; i++) {
for (int j = 0; j < ds.length; j++) {
String str = hs[i]+ds[j];
list.add(str);
}
}
list.add("大王");
list.add("小王");
return list;
}
//在pk集合中去除draw集合的元素
public static ArrayList<String> quChong(ArrayList<String> pk,ArrayList<String> draw){
for (int i = 0; i < draw.size(); i++) {
for (int j = 0; j < pk.size(); j++) {
if(draw.get(i)==pk.get(j)){
pk.remove(j);
}
}
}
return pk;
}
} |
|