0

My practice problem says to"this method returns an array that has the elements of the specified

 // array of Objects, with the Object at the specified index removed.

    // the returned array should be smaller by one and have all elements

    // in the same relative location to each other. YOU MAY NOT USE

    // A LIST :)

Object[] remove(int index, Object[] arr){"

I have come up with this so far, and I'm not entirely sure it works. Can you guys please take a look and give me some feedback on how to fix it so I can do this "remove" properly.

public static remove(int index, Object[] arr){
int counter = 0;
int temp = 2;
int[] arr = {1, 2, 3, 4};
int[] second = new int[arr.length-1];

    for(int i=0; i< arr.length;i++){
        if(i != temp){
            second[counter] = arr[i];
            counter ++;

        }
        //return second;
    }
7
  • remove needs a return type. Also, you never use the index parameter. Other than that, you're really close. Commented Feb 9, 2016 at 7:11
  • how should i incorporate the index part of it? Commented Feb 9, 2016 at 7:14
  • public static remove(int index, Object[] arr){ int counter = 0; int index = 2; int[] arr = {1, 2, 3, 4}; int[] second = new int[arr.length-1]; for(int i=0; i< arr.length;i++){ if(i != index){ second[counter] = arr[i]; counter ++; } //return second; } Commented Feb 9, 2016 at 7:15
  • index is the index of the element you want to remove. Looking at your code, you already know how to skip the index that you want to removed. You just called it the wrong thing. Commented Feb 9, 2016 at 7:16
  • so if i change temp to index, would this work as intended? Commented Feb 9, 2016 at 7:17

2 Answers 2

2
public static Object[] remove(int index, Object[] array) {
    Object[] newArray = new Object[array.length - 1];
    for (int i = 0; i < array.length; i++) {
        if (index > i) {
            newArray[i] = array[i];
        } else if(index < i) {
            newArray[i - 1] = array[i];
        }
    }
    return newArray;
}
Sign up to request clarification or add additional context in comments.

3 Comments

I made newArray according to the problem. Now you can return that array or do whatever you want with it.
I just updated my question with a second part, can you guys help me with that too? please
@chicagobears9023 you should consider selecting the best answer to your original question
0

You would have to copy over all elements, besides for the one at index, into a new array and return that.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.