difference method java using enum types

前端 未结 2 1635
暗喜
暗喜 2021-01-25 04:23

I wish to write a method that can return the difference in value of 2 cards. Im confused as I\'m learning enums and not sure of the most efficient way to implement it.



        
相关标签:
2条回答
  • public enum Rank {ACE(1), TWO(2); /* obviously add the other values*/
        private int value  ;
        Rank(int value){
            this.value = value;
        };
        public int getValue(){
           return this.value;
        }
    
        public int calcDifference(Rank rank){
            return getValue() - rank.getValue();
        }
    
    };
    

    which can then be called like so :

    Rank rankAce =  Rank.ACE;
    System.out.println(rankAce.calcDifference(Rank.TWO));
    

    You could remove the int value and just use ordinal, but this way gives you a bit of flexibility.

    0 讨论(0)
  • 2021-01-25 04:46

    The simplest way to define a value of a card is to add thirteen times the suit to the rank, or to add four times the rank to the suit:

    public int faceValue(Card c) {
        return 13*c.getSuit().ordinal()+c.getRank().ordinal();
    }
    

    or

    public int faceValue(Card c) {
        return 4*c.getRank().ordinal()+c.getSuit().ordinal();
    }
    

    Both ways produce numbers from 0 to 51, inclusive.

    With faceValue in hand, you can define the difference function as follows:

    public static int faceValueDifference(Card left, Card right){
        return left.faceValue()-right.faceValue();
    }
    
    0 讨论(0)
提交回复
热议问题