简体   繁体   English

检测数组中的重复项

[英]Detecting duplicates in an array

Pretty new to this and I've exhausted numerous attempts to figure out why this isn't working but can't get it. 对此还很陌生,我已经进行了无数次尝试,以弄清为什么它不起作用但无法实现。

private int indexOf(int searchingNum)
{
    int x = searchingNum;
    for (int i = 0; i<numberArray.length; i++){
        if (numberArray[i]==x)
            index = i;
        else
            index = -1;
    }
    return index;
}

public boolean addNumber(int numberToAdd)
{
    int x = numberToAdd;
    if (indexOf(x)!=-1)
        return false;
    if (count<numberArray.length&&indexOf(x)==-1){
        count++;
        numberArray[count-1] = x;
        return true;
    }

    if  (count>=numberArray.length&&indexOf(x)==-1){
        count++;
        newArray = Arrays.copyOf(numberArray, 2* numberArray.length);
        numberArray = newArray;
        numberArray[count-1] = x;
    }
    return true;    
}

The method should't allow for duplicates but does. 该方法不应允许重复,但可以。 Any pointers in the right direction would be much appreciated. 朝正确方向的任何指针将不胜感激。

Thank you. 谢谢。

Your indexOf is incorrect: since you continue the loop after finding a match, your code returns -1 unless the last item in the array happens to match. 您的indexOf不正确:由于找到匹配项后继续循环,因此代码返回-1除非数组中的最后一项恰好匹配。

To fix this problem, return i from inside the loop: 要解决此问题,请从循环内部返回i

for (int i = 0 ; i < numberArray.length ; i++) {
    if (numberArray[i]==x)
        return i;
}
// If we are here, we did not find anything; return -1
return -1;

Here's a precise version of your code : 这是您的代码的精确版本:

private boolean contains(int searchingNum)
{
    for (int i = 0; i<numberArray.length; i++){
        if (numberArray[i]==x)
            return true;
    }
    return false;
}

public boolean addNumber(int numberToAdd)
{
    int x = numberToAdd;
    if (contains(x))
        return false;
    if (count<numberArray.length){
        count++;
        numberArray[count-1] = x;
}
   else{
        count++;
        int []newArray = Arrays.copyOf(numberArray, 2* numberArray.length);
        numberArray = newArray;
        numberArray[count-1] = x;
    }
    return true;    
}

Try this. 尝试这个。 Meanwhile, it can only gurantee you the uniqueness of the elements if the array wasn't previously initialised, ie all elements are added in the array using this method only. 同时,如果未事先初始化数组,则只能保证元素的唯一性,即,仅使用此方法将所有元素添加到数组中。

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

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