gpt4 book ai didi

java - Java扑克游戏中的直手牌

转载 作者:行者123 更新时间:2023-12-02 06:14:05 25 4
gpt4 key购买 nike

我在完成扑克牌的直接方法时遇到困难。我不明白为什么我的代码不起作用。

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;

}

最佳答案

正如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;
}
}

关于java - Java扑克游戏中的直手牌,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21640541/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com