如果数组中的四个不同数字都相等,则该方法应该返回 true。但每当我尝试使用 4
相同的数字运行它时,我都会收到一条错误消息:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at Assignment4.containsFourOfaKind(Assignment4.java:93)
at Assignment4.main(Assignment4.java:16)
public static boolean containsFourOfaKind( int hand[] ){
for (int i = 0; i < 5; i++) {
if (hand[i ] == hand[i + 1] &&
hand[i + 1] == hand[i + 2] &&
hand[i + 2] == hand[i + 3]
) {
return true;
}
}
return false;
}
我该如何解决这个问题?
最佳答案
大多数答案仅解决 ArrayIndexOutOfBoundsException,但它们没有解决您的原始代码未检测到的问题。它试图检测四连胜。想象一下一只手 {3, 0, 3, 3, 3}
:即使你的代码没有导致 ArrayIndexOutOfBoundsException,它仍然会说这不是 4-of-a-kind,尽管很明显是这样。
您需要代码来实际计算同类的数量,然后检查总手牌中是否有四个或更多。 (在一副典型的扑克牌中,同种牌的数量不能超过 4 个,因此您也可以使用 ==
来检查是否为 4)
下面的代码甚至与手中的牌数无关,尽管从上面的代码来看,您的手牌大小为 5(这在扑克中非常典型)
public static boolean containsFourOfaKind(int hand[]) {
for (int i = 0; i < hand.length; i++) {
int countOfKind = 0;
for (int j = 0; j < hand.length; j++) {
if (hand[i] == hand[j]) {
countOfKind++;
}
}
if (countOfKind >= 4) {
return true;
}
}
return false;
}
(请注意,这是一种 native 方法。您可以进一步优化它;例如,如果您仔细观察,您会发现 i
不必比 0
和 1
。)
关于java - 如何检查数组中 4 个不同的数字是否彼此相等?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35387828/