-1

Without using arraylists, arraycopy, or any other imported method, but simply just using for loops and an additional array, how does one remove the first occurrence of a certain element?

this is my code so far:

public class remover {
public static void main(String[] args) {
     //initial array
    int[] oldArray = {1,2,3,4};

    //value to remove is 3


    //define the new array with smaller size
    int[] newArray = new int[oldArray.length];

    //cycle through array
    for(int i=0;i < oldArray.length;i++) 
    {
        if(oldArray[i] == 3) {
            for(int k=0; k<i; k++) {
                newArray[i] = oldArray[i];
            }
            for(int m=i; m<oldArray.length; m++) {
                newArray[m] = oldArray[m];
            }


        }

    }


for(int i=0; i<oldArray.length; i++) {
System.out.println(oldArray[i]);
}
}
}
6
  • 1
    What have you tried..?? Commented Oct 2, 2018 at 4:05
  • 1
    Welcome to SO! Are you trying to copy the old array to a new one without the target element or are you trying to modify the old array in-place? What if there are multiple matches for the element to remove? Remove them all or just the first? Commented Oct 2, 2018 at 4:06
  • Why do you have such odd, arbitrary requirements? Commented Oct 2, 2018 at 4:06
  • @Phil I think that question could be asked about most questions on SO. Commented Oct 2, 2018 at 4:07
  • @Adam too true, but why do you? Commented Oct 2, 2018 at 4:08

1 Answer 1

2

Loop through twice like this

    int[] oldArray = {1,2,3,3,4};

    int valToremove = 3;
    int numToRemove = 0;

    for (int x : oldArray) {
        if (x == valToremove)
            numToRemove++;
    }

    //define the new array with smaller size
    int[] newArray = new int[oldArray.length - numToRemove];

    //cycle through array
    int i = 0;
    for (int x : oldArray) {
        if (x != valToremove) {
            newArray[i] = x;
            i++;
        }
    }
Sign up to request clarification or add additional context in comments.

4 Comments

Hey, I'm only trying to do it for the first occurrence. Wouldn't this delete all occurrences from the array?
@Adam I was showing how to be flexible with your code. If you only have one element then this code would still work. If you want to change your requirements to only remove the first matching number then this can be easily achieved by adding a boolean variable alreadyRemoved = false which can be set to true when removed and the if becoming if (x != valToremove || !alreadyRemoved)
I tried your code, and got arrayoutofbounds with numtoremove at 0. when I changed it to 1, it changed every element in the array to 0
Yes, you should change int valToremove = 3;

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.