java 枚举举例:poker牌类

来源:互联网 发布:数据库开发和java开发 编辑:程序博客网 时间:2024/04/30 00:12

编写一个扑克类(每张扑克有花色和数值,例如红心A,草花10),将52张扑克牌放到集合中(自己去选择集合类)

编写3个方法

方法1.将集合中的所有扑克重新洗牌,并将扑克输出(打印出来即可)方法2.将集合中的所有扑克排序(按方块3~方块2,草花3~草花2, 红心3~红心2, 黑桃3~黑桃2的顺序排序)方法3:比较两张扑克牌的大小,如果版面的值相等,则按(黑桃->红心->草花->方块)的顺序进行排列

使用枚举内部类,定义poker类花色,完成poker类name的赋值

public class Pokers implements Comparable<Pokers>{    private int value;//值    private String name;//名字    private Type type;    public int getValue() {        return value;    }    public void setValue(int value) {        this.value = value;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public Type getType() {        return type;    }    public void setType(Type type) {        this.type = type;    }    public static enum Type{        黑桃(4),红桃(3),草花(2),方片(1);        private int v;        Type(int v){            this.v=v;        }        public int getV() {            return v;        }    }    public String toString() {        return "Poker ["+ name +"]";    }    public int compareTo(Pokers o) {        if(this.getValue()==o.getValue())            return this.getType().getV()-o.getType().getV();        return this.getValue()-o.getValue();    }}
package com.oracle.test.test17Collection;import java.util.ArrayList;import java.util.Collections;import java.util.HashSet;import java.util.List;import java.util.Set;public class TestPokers {    public static void main(String[] args) {        //Pokers [] pokerBox=new Pokers[52];        Set<Pokers> pk=new HashSet<Pokers>();        ArrayList<Pokers> li=new ArrayList<Pokers>();        //int index=0;        for(int i=1;i<=13;i++){            for(Pokers.Type pt:Pokers.Type.values()){                Pokers p=new Pokers();                p.setValue(i);//设置值1~13                p.setType(pt);//设置花色4个                switch(i){                case 1:p.setName(pt.name()+"A");break;                case 11:p.setName(pt.name()+"J");break;                case 12:p.setName(pt.name()+"Q");break;                case 13:p.setName(pt.name()+"K");break;                default : p.setName(pt.name()+i);                }                //pokerBox[index++]=p;                pk.add(p);                li.add(p);            }        }//      for(Pokers p:pokerBox){//          System.out.println(p.getName());//      }//      int result=compare(pokerBox[0],pokerBox[1]);//      System.out.println(result+" ==");        System.out.println(pk);        Collections.sort(li);        //Collections.shuffle(li);        System.out.println(li);    }    public void sort(List<Pokers> pokers){        Collections.sort(pokers);    }    public static int compare(Pokers p1,Pokers p2){        if(p1.getValue()==p2.getValue()){            return p1.getType().getV()-p2.getType().getV();        }        else            return p1.getValue()-p2.getValue();    }}

运行结果:
这里写图片描述

0 0
原创粉丝点击