vendredi 21 septembre 2018

Boolean Method with a comparison nest loop for an array how to fix

So i have a assignment to create a boolean method that returns true or false if there is a duplicate integer within a given array of integers. the problem is the only way to check is to take each element and compare it with the others, kinda like insertion sort almost. the problem is that it cant read my result variable saying it isnt initiated Here is the code:

public static boolean hasDuplicate(int numOfElement, int[] numArr)
    {
    int numOfElements = numOfElement;
    int[] uncheckedArr = numArr;
    boolean result;

    for( int i = 0 ; i < numOfElement; i++) // takes an element in order from left to right
    {
        for(int j = i + 1; j < numOfElement; j++)
        {
            if (numArr[i] == numArr[j])
                result = true;
        }


    }
    return result;
}

My Question is how can i fix this? I want to have it stop as well once it detects a duplicate within the array. however i know break function only does the most inner loop. This is only a small layout as i kept changing the code a lot. I did try looking up this stuff online but cant seem to find the solution

Aucun commentaire:

Enregistrer un commentaire