如何检查数组中的4个不同数字是否相等?

时间:2016-02-14 02:50:32

标签: java

如果数组中的四个不同数字全部相等,则此方法应返回true。但每当我尝试使用4相等的数字运行它时,我会收到一条错误消息:

  

线程中的异常" main" java.lang.ArrayIndexOutOfBoundsException:5
  在Assignment4.containsFourOfaKind(Assignment4.java:93)
  在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;
}

我该如何解决这个问题?

8 个答案:

答案 0 :(得分:1)

当您从int main () { string dep = "Deposit"; string with = "Withdrawl"; string bal = "Balance"; char choice; cout << "PLease enter options A, B, C, or Q to quit.\n"; cin >> choice; switch (choice) //to make them all the same, same as using toUpper { case 'a': case 'A': cout << ""; break; case 'b': case 'B': cout << ""; break; case 'q': case 'Q': cout << ""; break; } int count = 1; while (count <= 4) { if (choice == 'a' || 'A' ) cout << dep << endl; else if (choice == 'b' || 'B' ) cout << with << endl; else if(choice == 'c' || 'C' ) cout << bal << endl; else (choice !='a' && choice !='b' && choice !='c'); cout << "that is invalid, PLease enter options A, B, C, or Q to quit.\n"; ++count ; } system ("PAUSE"); return 0; } 运行循环时,您正在检查五个值...在(i=0; i<5;...)语句中,您正在查看if。这意味着在迭代期间hand[i] == hand[i+1] && hand[i+1] == hand[i+2] && hand[i+2] == hand[i+3]您尝试访问i=4hand[4]时。

我怀疑你的数组hand[7]没有那么多元素。

答案 1 :(得分:1)

public static boolean containsFourOfaKind(int hand[]){
  for(int x=0; x < hand.length; x++){
    for(int y=0; y < hand.length; y++){
      if(y!=x){
        if(hand[x]!=hand[y]){
           return false;
        }
      }
    }
  }
  return true;
}

你在循环中使用+1进入索引之外。上面的代码检查数组中的所有元素是否相同。

答案 2 :(得分:1)

虽然其他人已经非常清楚地解决了ArrayIndexOutOfBoundsException,但我还想提出另一种不使用索引的方法:

    private boolean isArrayEqual(int[] array) {
        Arrays.sort(array);  //Sort array to place four of a kind in sequence

        int[] setOfFour = Arrays.copyOfRange(array, 0, 4);  //Copy first four values
        int[] compareArray = new int[4];

        Arrays.fill(compareArray, setOfFour[0]);  //Make an array containing only first value
        if (Arrays.equals(compareArray, setOfFour)) {  //Test if first four are equal
            return true;
        } else { //Test is last four are equal
            setOfFour = Arrays.copyOfRange(array, 1, 5);  //Copy of last four values
            Arrays.fill(compareArray, setOfFour[0]);
            return Arrays.equals(compareArray, setOfFour);
        }
    }

你创建了第二个数组,其中填充了所讨论数组中的一个值(任何值都可以 - 我选择了第一个)。然后看看数组是否相等。完成。

答案 3 :(得分:1)

大多数答案仅解决ArrayIndexOutOfBoundsException,但它们并未解决原始代码未检测到的问题。它试图检测四排。设想一只手{3, 0, 3, 3, 3}:即使你的代码没有引起ArrayIndexOutOfBoundsException,它仍然会说这不是四种类型,尽管它显然是。

您需要的代码实际上会计算出有多少类型的代码,然后检查它是否是总数中的四个或更多。 (在典型的扑克牌套牌中,你不能超过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;
}

(请注意,这是一种原生方法。您可以进一步优化这一点;例如,如果仔细观察,您会发现i不得超过0 {1}}和1。)

答案 4 :(得分:0)

//brain compiled code
public static boolean containsFourOfaKind(int hand[])
{ 
    for(int i=0; i < hand.length - 1; i++) 
    {
        if(hand[i] != hand[i + 1])
            return false;
    }

    return true;
}

按照你的方法,你可以进行一次非迭代的简单检查,只检查所有四张卡是否相等,但是如果你要采用迭代方法那么这可能是你的最好的选择。每当你收到一个arrayindexoutofbounds异常时,你总是知道它与你的数组有关,在你的情况下,只有一个地方处理数组,所以一旦你知道异常意味着它就应该很容易可视化。

非演绎方法如下......

//brain compiled code
public static boolean containsFourOfaKind(int hand[])
{ 
    if((hand[0] == hand[1]) && (hand[1] == hand[2]) && (hand[2] == hand[3]))
        return true;

    return false;
}

可以使用,但不推荐使用。

答案 5 :(得分:0)

一种不专门针对一只手的方法,可能是针对一个更大的群体;数组可能远大于4。在这种情况下,您可以在地图上添加一个循环,计算某个&#34;对象&#34;的数量。 (字面含义)在该列表中:

public static boolean fourOfaKind(Integer[] hand) {
  HashMap<Integer,Integer> counts = new HashMap<Integer,Integer>();
  for(Integer i : hand) {
    if(counts.containsKey(i)) 
        {
            int count = counts.get(i);
            counts.put(i, ++count);
            if(count >= 4)
                return true;
        }
        else
            counts.put(i, 1);       
      }
  return false;
}

答案 6 :(得分:0)

简单代码可以如下,这将适用于N个元素。

public static boolean containsFourOfaKind(int hand[]){

        for(int i=1; i < hand.length; i++){
            if(hand[i-1] != hand[i]){
                return false;
            }
        }
        return true;
    }

答案 7 :(得分:-1)

在Java8中,您可以轻松完成:

private static boolean isEqualElements(int[] arr) {
    return Arrays.stream(arr).allMatch(value -> arr[0] == value);;
}
相关问题