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;
}
user1062898
  • 109
  • 2
  • 2
  • 10
  • 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?](http://mattgemmell.com/2008/12/08/what-have-you-tried/) – Andrew Thompson Dec 15 '11 at 01: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]? – BillRobertson42 Dec 15 '11 at 01: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 – user1062898 Dec 15 '11 at 01: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). ;) – Andrew Thompson Dec 15 '11 at 01:50
  • Then wouldn't you need to resize the target array? The original has 8 elements, and the new has 9. – BillRobertson42 Dec 15 '11 at 01:50

2 Answers2

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.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
0
myArray[i+1] = myArray[i];

Maybe this will help you.

Pritom
  • 1,294
  • 8
  • 19
  • 37