Home > Mobile >  Shift array elements java
Shift array elements java

Time:03-28

I've got Method to shift arr elements:

 private static int[] shiftElements(int[] arr, int n) {
        for (int i = 0; i < arr.length; i  ) {
            arr[i n] = arr[i];
        }
        return arr;
    }

n - amount of shifting.

When I execute this code I've got an exception:

    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6

As far as I understand program need more space to contain another item. But I don't need to added more item, I need shift already existing. With nparameter, if parameter negative all array moving to left, if positive to right, if zero - nothing happen.

Examples


ORIGINAL ARRAY: 1,3,5,6,8,10

example: 
n = 2
arr: 8,10,1,3,5,6

How to achieve it?

CodePudding user response:

Your exception comes from this line:

arr[i n] = arr[i];

You get an exception because i n > arr.length.

From your example, you want those elements that would end up outside the array to be added at the front instead.

I won't do your homework for you, but you might want to use an if(...) for that. Or a mod expression...

  • Related