直接参与Java扑克游戏

时间:2014-02-08 01:06:41

标签: java

我无法完成扑克牌的直接方法。我不明白为什么我的代码不起作用。

public static boolean containsStraight(int [] hand)
{
boolean straight = false;
for(int i = 0; i < 5; i++)
{
  if (hand[i] == 2 && hand[i] == 3 && hand[i] == 4 && hand[i] == 5 &&               hand[i] == 6)
  {
    straight = true;
  }
  if (hand[i] == 3 && hand[i] == 4 && hand[i] == 5 && hand[i] == 6 && hand[i] == 7)
  {
    straight = true;
  }
  if (hand[i] == 4 && hand[i] == 5 && hand[i] == 6 && hand[i] == 7 && hand[i] == 8)
  {
    straight = true;
  }
  if (hand[i] == 5 && hand[i] == 6 && hand[i] == 7 && hand[i] == 8 && hand[i] == 9)
  {
    straight = true;
  }
}
return straight;

}

3 个答案:

答案 0 :(得分:2)

你说在每次迭代中,手[i]必须是2和3和4和5.这是不可能的。手中只有一个数字[i]。

答案 1 :(得分:0)

正如pL4Gu33在他的回答中所述,你的比较是错误的。从本质上讲,通过for循环的每一步都会使hand[i]保持恒定值(例如,4)。这意味着你的if语句正在检查:

if(4 == 4 && 4 == 5 && 4 == 6 && 4 == 7 && 4 == 8) {
    ...
}

这将永远不会评估为true。如果您确定手中有五个元素并且手已经排序,那么可以

if (hand[0] == 2 && hand[1] == 3 && hand[2] == 4 && hand[3] == 5 && hand[4] == 6) {
    ...
}

但是,我会给你一个更好的答案。

你应该做的第一件事是分手。一旦你这样做,很容易一步一步地检查手中的下一张牌是否正好比前一张牌大一张。如果你到了最后并且这是正确的,那么它就是直的。

/*
 * You will need to import java.util.Arrays
 */

public boolean isStraight(int[] hand) {

    if(hand == null || hand.length != 5) {
        return false;
    }
    else {
        // Automatically sort the hand
        Arrays.sort(hand);

        // Set the "previous" variable to a theoretically impossible value
        int prev = -1;

        // Iterate through the hand and see if the next card is exactly one more than
        //    the previous one.
        for(int i = 0; i < hand.length; i++) {

            // If prev is -1, then this is the first time through the for-loop
            // If the card that we're on has a value of the previous card + 1,
            //     we still have the possibility of a straight.
            if(prev == -1 || (prev + 1) == hand[i]) {
                prev = hand[i];
            }
            else {
                return false;
            }
        }
        return true;
    }
}

答案 2 :(得分:0)

问题是,您正在错误地使用循环,因为您始终在hand[i]中检查同一张卡的值。我的建议是先做一个排序,或者如果你想提高效率,你可以使用第二个布尔字段,这表明你手中是否有一张给定值的卡片。这样你就可以轻松检查,如果你有成功的任意数量的卡。

public static boolean containsStraight(int[] cards) {

    int count = 0;
    boolean[] valueInHand = new boolean[10];

    for (int card : cards) {
        valueInHand[card] = true;
    }

    for (boolean value : valueInHand) {
        if (value == true) {
            count++;
        } else {
            count = 0;
        }
        // works for any number of cards
        if (count == cards.length) {
            return true;
        }
    }
    return false;
}
相关问题