1

Looked around, couldn't find any similar questions in java..

Basically I need to add a number to an int array in a specific position index

I can only use Arrays, no ArrayLists

Here is what I have so far, and I know why it doesn't work, but I can't figure out how to fix that problem of overwriting, which I don't want it to do.

The task is a non-overwriting insert. e.g. the final result would be

[1 2 1337 3 4 5 6 7 8]

Here is the code snippet:

public void main(String[] args)
{
int[] array = {1,2,3,4,5,6,7,8};
array = add(array, 2, 1337);
for(int i : array)
    System.out.print(i + " ");
}


public int[] add(int[] myArray, int pos, int n)
{
    for (int i = pos; i<myArray.length-1; i++){
        myArray[i] = myArray[i+1];
    }
    myArray[pos] = n;
    return myArray;
}
5
  • 4
    Is this homework? "I can't figure out how to fix that problem." What is the problem? Note that "doesn't work" is of no use in describing the problem. What is your best theory on solving it? What have you tried? Commented Dec 15, 2011 at 1:37
  • 1
    Do you mean a non-overwriting insert? e.g. the final result would be [1 2 1337 3 4 5 6 7 8]? Commented Dec 15, 2011 at 1:41
  • that problem, being the fact that it isn't adding it to the array, and that was my best theory on solving it... @Bill Yes Commented Dec 15, 2011 at 1:42
  • OK, again. Is this homework? If so, it should be tagged as such, and would attract more 'followers' than the last 4 tags combined. Aaah yes. 288 (last 4 tags combined followers) vs. 862 (homework). ;) Commented Dec 15, 2011 at 1:50
  • Then wouldn't you need to resize the target array? The original has 8 elements, and the new has 9. Commented Dec 15, 2011 at 1:50

2 Answers 2

2

Your problem is this loop:

for (int i = pos; i<myArray.length-1; i++){
    myArray[i] = myArray[i+1];
}

It is writing i+1 into i - ie it moves element down - you need it to move them up. In order to move up, you need to iterate down (otherwise you overwrite what you just wrote).
Try this:

for (int i = myArray.length - 1; i > pos; i--) {
    myArray[i] = myArray[i - 1];
}

Note that this will make room for the insertion at pos by losing (overwriting) the last element.

Sign up to request clarification or add additional context in comments.

1 Comment

This was exactly what I needed this loop to do, now I can continue with my project thanks!
0
myArray[i+1] = myArray[i];

Maybe this will help you.

1 Comment

That will end up replacing the rest of the array with myArray[i], which overwrites the data.

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.