-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.

Juan Carlos Mendoza
  • 5,736
  • 7
  • 25
  • 50
Eliyo
  • 3
  • 1

2 Answers2

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.

Marcos Vasconcelos
  • 18,136
  • 30
  • 106
  • 167
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?

jurez
  • 4,436
  • 2
  • 12
  • 20