-4

I was hoping i could get some help concerning, how to move an element of an array, one index over. so that Array[0] is on Array[1] place and Array[1] is on Array[2] place and so on. The code i have so far does not want to run:

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

for(int i = 0; i < p.length; i++) {
    p[i + 1] = p[i];
}

Any guidance would be appreciated.

3
  • What should happen to the index 4? Should it go to 0? Or should it move to index 5? Commented Oct 9, 2017 at 19:06
  • index 4 should move to index 5, even though there isnt one Commented Oct 9, 2017 at 19:15
  • @Eliyo Index 4 should never move to index 5. No one can make that happen because that will be ArrayIndexOutOfBoudsException. Commented Oct 9, 2017 at 20:18

2 Answers 2

1

The easiest is using a circular counter

int[] p = {1, 2, 3, 4, 5};
int[] r = new int[p.length];
for(int i = 0; i < p.length; i++) {
    r[(i + 1) % p.length] = p[i];
}

Thats ensure that index will be inside the lenght of p.lenght and i+1 will be 0

Also note that I created a array for the result, cause else you would need to keep a reference of the last swaped int at index to set, cause you will replace it value by loop.

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

1 Comment

I think you mean p.length in the line inside your for-loop.
1

First, you need to correct the upper bound in your for loop. As you have it, you'll get ArrayIndexOutOfBoundsException, because i + 1 will be over last element.

Second, if you want to move elements from i to i+1, you have to loop backwards. Otherwise, you'll keep overwriting the next element. If you can't see that, try doing in on paper.

Third, you might want to use System.arrayCopy, which is almost certainly faster.

And last, "code does not want to run" is a completely useless information. How do you run it, what exceptions do you get, what did you try?

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.