2

I've written a code for removing the number from an array. When I run my code, it happens not to remove the number but instead gives me another number. For example, when I pass number 44 in order to remove it, the ouput happens to be 3 instead of removing it. What could be the problem?

Given input:

2 5 33 44 3 8 6 7 4 

Sample output:

2 5 33 3 3 8 6 7 4 

Code:

public class RemoveAtIndex {

    public static void main(String[] args)
    {
        int[] myArray = {2, 5, 33, 44, 3, 8, 6, 7, 4};
        int[] output = removeFromIndex(myArray, 44);
        for(int i = 0; i < output.length; i++)
        {
            System.out.print(output[i] + " ");
        }

    }

    public static int[] removeFromIndex(int[] myArray, int num)
    {
        int[] resultArray = new int[myArray.length - 1];
        for(int i = 0; i < myArray.length; i++){
            if(myArray[i] != num){
                resultArray[i] = myArray[i]; 
            }
            else
                resultArray[i] = myArray[i+1];
        }
        return resultArray;
    }
}
2
  • Have you tried using a debugger to see how your program behaves? Commented Jun 20, 2015 at 19:28
  • You just duplicated one number instead of shifting all indices by one. Furthermore, I doubt that your sample input and sample output are generated by the program. Both have a length of 9. Commented Jun 20, 2015 at 19:32

3 Answers 3

1

Your code will throw ArrayIndexOutOfBoundExceptionas the length of two arrays are different and you are using the same variable i to iterate when assigning in the for-loop

So I've modified the code as i for one array and j for other array as

public static int[] removeFromIndex(int[] myArray, int num) {
        int[] resultArray = new int[myArray.length - 1];
        for (int i = 0, j = 0; i < myArray.length; i++) {
            if (myArray[i] != num) {
                resultArray[j++] = myArray[i];
            }
        }
        return resultArray;
    }
Sign up to request clarification or add additional context in comments.

6 Comments

I was about to post this same hing
Could you please explain the logic of this line: resultArray[j++] = myArray[i];? What does it do when the matching number is found? Thanks in advance! @Madhan
add values to resultArray and iterate to next index. As you see the i myArray index will be incremented for each iteration. we need to increment the j resultArray only if it matches the condition
@Madhan, but does it mean if myArray[i] == num then it skips the number?
NEVERMIND! Figured out everything! Thank you!
|
0

Try:

 public static int[] removeFromIndex(int[] myArray, int num)
 {
    int[] resultArray = new int[myArray.length - 1];
    for(int i = 0; i < myArray.length; i++){
       if(myArray[i] != num){
          resultArray.push(myArray[i]); 
       }
       else{
          return myArray;
       }

       return resultArray;
    }
}

You might have to include stack.push class

Comments

0

You're dealing with arrays of different size so you'll need two separate indexes when you're assigning the contents from the old array to the new array with the number of interest removed.

public static void main(String[] args) throws Exception {
    int[] myArray = {2, 5, 33, 44, 3, 8, 6, 7, 4};
        int[] output = removeFromIndex(myArray, 44);
        System.out.println(Arrays.toString(output));
}

public static int[] removeFromIndex(int[] myArray, int num) {
    // Index counter for the new array
    int index = 0;
    int[] resultArray = new int[myArray.length - 1];
    for (int i = 0; i < myArray.length; i++) {
        // Skip the element that matches the number wanting to be removed
        if (myArray[i] == num) {
            continue;
        }

        resultArray[index] = myArray[i];
        index++;
    }
    return resultArray;
}

Results:

[2, 5, 33, 3, 8, 6, 7, 4]

Are you allowed to use Java 8? If so you can just do the removal process with one line and get the same results.

public static void main(String[] args) throws Exception {
    int[] myArray = {2, 5, 33, 44, 3, 8, 6, 7, 4};
        int[] output = removeFromIndex(myArray, 44);
        System.out.println(Arrays.toString(output));
}

public static int[] removeFromIndex(int[] myArray, int num) {
    return Arrays.stream(myArray).filter(n -> n != num).toArray();
}

3 Comments

Could you please explain the logic of these lines:resultArray[index] = myArray[i]; index++; If the matching number is found, does it simply skip it and overwrites it? @Shar1er80
@John You're original array has elements from indexes 0 - 8, the new array will have elements from 0 - 7. If you try to just do a straight copy over from the old array to the new array, you'll result in an IndexOutOfBoundsException. That's why you need two separate index counters. 1 index counter that will go through the old array (This is the variable i in the for loop) and 1 index counter that will go through the new array (This is the variable index).
@John If you're allowed to use Java 8, you can avoid separate counters using streams if try using the additional answer I provided.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.