+ 2

Explanation about what's wrong.

//Output should swap 2 positions, I can't explain myself why this code doesn't function. class ArrayTools { public static void main(String[] args) { int[] array = {1,2,3,4,5}; //Test int[] swap = swap(array,2,4); for (int i=0; i<swap.length; i++) System.out.print(swap[i]); } public static int[] swap(int[] a, int i1, int i2) { int[] swap = new int[]; for (int i=0; i<a.length; i++) { if(swap[i] == a[i1]) swap[i] = a[i2]; else if(swap[i] == a[i2]) swap[i] = a[i1]; else swap[i] = a[i]; } return swap; } //OUTPUT: 12345 } /* Here is a code that is functioning well but I think it's not effcient to write it first and replace it right after it, so the CPU have to declare it 2 times instead of once.: swap[i] = a[i]; if(swap[i] == a[i1]) swap[i] = a[i2]; else if(swap[i] == a[i2]) swap[i] = a[i1]; //OUTPUT: 12543 */

28th Feb 2019, 8:52 PM
Yusuf Acikyol
Yusuf Acikyol - avatar
1 Réponse
+ 3
This doesn't explain my Question actually..
1st Mar 2019, 7:09 AM
Yusuf Acikyol
Yusuf Acikyol - avatar