I try to sorting a double array.An odd element should ascending order.An even element should descending.My classes is as follow. When I runned project I show
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
package com.fatih.sortarray;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class SortingArray {
public static Double[] sortItOut(Double[] array) {
Double[] arrayOdd = {};
Double[] arrayEven = {};
Double[] sortedArray = {};
for (int i = 0; i < array.length; i++) {
int k = 0;
int j = 0;
if (array[i] % 2 == 0) {
arrayOdd[k] = array[i];
k++;
} else {
arrayEven[j] = array[i];
j++;
}
}
Arrays.sort(arrayOdd, Collections.reverseOrder());
Arrays.sort(arrayEven);
List list = new ArrayList(Arrays.asList(arrayOdd));
list.addAll(Arrays.asList(arrayEven));
sortedArray = (Double[]) list.toArray();
return sortedArray;
}
}
....
public class SortingArrayTestt {
public static void main(String[] args) {
Double[] array = { 1d, 2d, 3d, 4d, 5d, 6d, 7d, 8d, 9d };
Double[] sortingArray = SortingArray.sortItOut(array);
for (int i = 0; i < sortingArray.length; i++) {
System.out.print(sortingArray[i]);
}
}
}
...
The console output is:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at com.fatih.sortarray.SortingArray.sortItOut(SortingArray.java:25)
at com.fatih.sortarray.SortingArrayTestt.main(SortingArrayTestt.java:9)
How can I fix this error? Thanks for everything.