+ 1
swap values in array
import java.util.Arrays; public class Solution{ public static void main(String[] args){ for(int x:swapValues(new int[]{111,77,88,44,32,11,13,25,44})) System.out.print(x+" "); } public static int[] swapValues(int[] a){ int temp; for(int i=0;i<a.length;i=i+2){ temp=a[i]; a[i]=a[i+1]; a[i+1]=temp; } return a; } } when I run the code it shows ArrayIndexOutOfBoundsException how to solve it?
1 Answer
+ 1
Change loop to:
for(int i=1;i<a.length;i++){
temp=a[i-1];
a[i-1]=a[i];
a[i]=temp;
}