检查当前枚举的枚举

时间:2017-03-17 17:05:27

标签: java enums

在制作纸牌游戏时,我来到了Straight,这些数字被设置为enum ace,两个,三个等等,我就像这样写了

List<Number> number = Arrays.asList(Number.two, Number.two, Number.three, Number.four, Number.five);

private void Straight() {
    for(int currentCard = 0; currentCard < 4; currentCard++){
        for(int searchCard = 0; searchCard < 4; searchCard++){
        if (number.get(searchCard) == number.get(currentCard ++)){
            if (number.get(searchCard ++) == number.get(currentCard + 2)){
                if (number.get(searchCard + 2) == number.get(currentCard + 3)){

                }
            }
        }


        }

看着这个,我看到currentCard将循环通过手而不是我想要的枚举集。哪种方式最有效率

编辑: 我试着编写一些像这样的代码

Number currentCard = number.get(0);

但是就像我预期的那样,它不等于整数值,现在我想知道是否有某种方法将它等于一个整数。

1 个答案:

答案 0 :(得分:0)

使枚举变得特别的主要原因之一是它们可以与==基本类型进行比较。尝试循环使用枚举令牌而不是整数。

List<Number> playerHand = Arrays.asList(Number.two, Number.two, Number.three, Number.four, Number.five);

public boolean isStraight(List<Number> hand) {
   int straightPosition = 0;
   boolean inStraightRun = false;
   Number lastStraightCard;
   for (int i = 0; i < Number.values().length; i++) {
       Number card = Number.values()[i];
       if (!inStraightRun) {
           if (card == hand[straightPosition]) {
               inStraightRun = true;
               lastStraightCard = card;
               straightPosition++;
           }
           else if (card == Number.ten) {
               break;//straight no longer possible
           }
       }
       else {
           if (card == hand[straightPosition] &&
               lastStraightCard == Number.values()[i - 1]) {
               lastStraightCard = card;
               straightPosition++;
           }
           else {
               break;//straight no longer possible
           }

           if (straightPosition > hand.length() - 1) {
               break;//straight! Stop looping
           }
       }
   }
   return straightPosition == hand.length();
}