+ 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?

12th Feb 2019, 1:09 PM
jyomendra prajapati
jyomendra prajapati - avatar
1 Réponse
+ 1
Change loop to: for(int i=1;i<a.length;i++){ temp=a[i-1]; a[i-1]=a[i]; a[i]=temp; }
13th Feb 2019, 12:59 AM
Lambda_Driver
Lambda_Driver - avatar