Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Shift array elements java

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Examples


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

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

How to achieve it?

>Solution :

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…

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading