2

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.

1
  • If you want to avoid duplicates, consider using a Set instead of an array. Commented Feb 18, 2017 at 20:32

2 Answers 2

2

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.

To fix this problem, return i from inside the loop:

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;
Sign up to request clarification or add additional context in comments.

1 Comment

I can't believe I didn't see that! Thank you! Problem resolved.
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, i.e. all elements are added in the array using this method only.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.