/*
2.扑克牌使用集合完成
3.方法调用
*/
import java.util.*;
class Test8
{
public static void main(String[] args)
{
//得到扑克牌
List<Poker> list=PokerUtil.getPokers();
PokerUtil.xipai(list);
PokerUtil.showPokers(list);
System.out.println("----------------------------------");
Poker p=new Poker("10","红桃");
int index=PokerUtil.findPoker(list,p);
if(index==-1){
System.out.println("没有这张扑克牌 "+p);
}else{
System.out.println(p+" 在"+(index+1)+"位置");
}
}
}
//声明扑克类
class Poker
{
String number;
String color;
public Poker(){}
public Poker(String number ,String color){
this.number=number;
this.color=color;
}
public boolean equals(Object obj){
Poker p=(Poker)obj;
return p.number.equals(number)&&p.color.equals(color);
}
public String toString(){
return color+number;
}
}
//扑克牌工具类
class PokerUtil
{
public static final String[] ns={"2","3","4","5","6","7","8","9","10","J","Q","K","A"};
public static final String[] cs={"黑桃","红桃","方块","梅花"};
//查找某张牌
public static int findPoker(List<Poker> list,Poker p){
return list.indexOf(p);
/*
List集合在使用indexOf方法时,是用参数与集合中所有元素进行equals ,
因为List是有顺序的,在比较时,从头到尾依次比较,如果集合中有一个元素
与参数equals为true,那么就将这个元素索引返回。如果集合中没有,那么返回-1;
*/
}
//洗牌
public static void xipai(List<Poker> list){
Random ran=new Random();
for(int i=0;i<100;i++){
int n1=ran.nextInt(list.size()); //0-52
int n2=ran.nextInt(list.size());
Poker p1=list.get(n1);
Poker p2=list.get(n2);
//将n1与n2位置上的元素进行交换.
list.set(n1,p2);
list.set(n2,p1);
}
}
//显示扑克
public static void showPokers(List<Poker> list){
for(int i=0;i<list.size();i++){
if(i%ns.length==0){
System.out.println();
}
System.out.print(list.get(i)+" ");
}
}
//得到52张扑克牌
public static List<Poker> getPokers(){
List<Poker> list=new ArrayList<Poker>();
for(int i=0;i<cs.length;i++){
for(int j=0;j<ns.length;j++){
//Poker p=new Poker();
//p.number=ns[j];
//p.color=cs[i];
//list.add(p);
list.add(new Poker(ns[j],cs[i]));
}
}
return list;
}
}
|