Reputation: 385
I'm trying to create a simple method to move the first element in an array to the back of the array.
Here's my code
public class Ex5_ShiftLeft {
public static void main(String[] args) {
int[] a = new int[] {6, 2, 5, 3};
swap (a);
}
public static void swap(int[] array){
array[0] = array[array.length];
System.out.println(Arrays.toString(array));
}
}
Eclipse doesn't seem to detect an error with my code, but when I run it, I get the error text
"Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4 at apollo.exercises.ch04_loops.Ex5_ShiftLeft.swap(Ex5_ShiftLeft.java:19) at apollo.exercises.ch04_loops.Ex5_ShiftLeft.main(Ex5_ShiftLeft.java:1)"
Any tips?
Upvotes: 2
Views: 126
Reputation: 460
I take it as you're a beginner so i'll say just keep at it and you'll sure improve. I improved your code below for you:
public class Ex5_ShiftLeft {
public static void main(String[] args) {
int[] a = {6, 2, 5, 3};
swap (a);
}
public static void swap(int[] array){
int temp = array[0]
array[0] = array[array.length-1];
array[array.length-1]
for(int x : array){
System.out.println(x+" ");
}
}
}
CHANGES: You can declare an array just with this: int[] myArray = {6,2,5,3};
There was a problem with your swap function. You have to create temporary variable so you can swap the first element of the array with the last.Also, the last element of the array is array[array.length-1]
Second, I used an Enhanced For-loop to print out the array. Hope this helps
Upvotes: 2
Reputation:
Use array[0] = array[array.length - 1];
to access the last item in the Array
.
Upvotes: -1
Reputation: 2789
The size of an array is basically static. For this purposes, you can use an ArrayList which is dynamic.
Upvotes: 0
Reputation: 624
The error is because of line :
array[0] = array[array.length];
If you want to access the last element of the array and populate it to array[0] then use below
array[0] = array[array.length-1];
Upvotes: -1
Reputation: 2337
Arrays represent a segment of memory which your program has reserved to store a series of numbers or whatever else your array has. Because of this, arrays cannot be resized; you can't go past the end of the segment of memory you've reserved because another program might be using that memory. Your solution does not work because it tries to take the first element and put it after the end of the array, which is out of bounds. Instead, you have to remember the first element, then move each element except for the first one space to the left to create room at the end of the array, and then you can put the first element at the end of the array.
Upvotes: 2