简体   繁体   English

Java 嵌套循环检查数组中的元素是否匹配

[英]Java nested loops to check if elements in an array match

Object class loop ( array1 and array2 are the arrays): Object class 循环( array1array2是数组):

public int howManyMatches(int[] array2){
    int count = 0;

    for (int i = 0; i < array2.length; i++) 
    {
        for (int j = 0; j < array1.length; j++)
        {
            if (array2[i] == (array1[j]))
            {
                count++;   
            } 
        }
    }
    return count;
}

Main class checking:主要 class 检查:

for (int i = 0; i < ticketArray.length; i++)
{
    int count = ticketArray[i].howManyMatches(array2);

    if (count == 4) 
    {
        System.out.println("All 4 elements match");
    }

    else if (count == 3)
    {
        System.out.println("Match 3");
    }

    else
    {
        System.out.println("Arrays do not match.");
    }
}

Loop only returns the else statement, even if the arrays are all matching.循环只返回else语句,即使 arrays 都匹配。 array1 is an input based array, and array2 is hardcoded. array1是一个基于输入的数组,而array2是硬编码的。

You can use a binary search您可以使用二进制搜索

    private int[] array1;
    // Arrays.sort(array1); if array1 not chaning sort it once here
    public int howManyMatches(int[] array2) {
        int count = 0;
        Arrays.sort(array2);
        // Arrays.sort(array1); if array1 changing sort it here
        for (int i = 0; i < array2.length; i++) {
            int index = Arrays.binarySearch(array1, array2[i]);
            if (index >= 0)
                count++;
        }
        return count;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM