简体   繁体   中英

Java nested loops to check if elements in an array match

Object class loop ( array1 and array2 are the arrays):

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:

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. array1 is an input based array, and array2 is hardcoded.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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