【发布时间】:2018-08-12 07:41:51
【问题描述】:
我正在尝试提出一种解决方案,只对数组中的奇数进行排序,同时保持偶数不变。为了做到这一点,我尝试将给定数组中的所有奇数删除到一个新数组中(odd_arr)并填充我插入一个大数(9731)的空白,以便我知道我应该在哪里插入回奇数一旦这些奇数被排序。
(只是为了理解 Ex: If array is {5,3,2,8,1,4} then step1:odd_arr will be {5,3,1} and array是 {9731,9731,2,8,9731,4} step2:排序后的 odd_arr 将是 {1,3,5} step3:最后用排序后的奇数替换主数组中的数字'9731',输出应该是数组是{1,3,2,8,5,4})。
这是我给出 ArrayIndexOutOfBoundException 的代码:
class Test {
public static int[] sortArray(int[] array) {
int[] odd_arr = new int[50];
int k =0;
for(int i :array){
if(array[i] % 2 == 1)//Exception producing at this line{
odd_arr[k] = array[i];
array[i] = 9731;
k = k+1;
}
}
Arrays.sort(odd_arr);
int j=0;
for(int i:array){
if(array[i] == 9731){
array[i] = odd_arr[j];
j = j+1;
}
}
return array;
}
public static void main(String[] args) {
int[] array = {5, 3, 2, 8, 1, 4};
int[] sorted_array = sortArray(array); //Exception here too
for(int i=0; i<sorted_array.length;i++)
System.out.print(sorted_array[i] + " ");
}
}
【问题讨论】:
-
您提供的代码无法编译。你能更新你的问题吗?
-
数组索引从 0 到数组大小 -1(在您的示例中为 0 到 5)。不是数组的值。
-
您正在使用增强的 for 循环语法
for (int i : array),而您应该使用常规的 for 循环for (int i = 0; i < array.size(); ++i)。查看this section in the Java Tutorials 了解其中的区别。 -
它不起作用,因为您使用增强的 for 循环(它返回数组的项目,不是索引)并使用返回的项目从名单。如果你的列表包含
3, 6, 123,它会在第一个崩溃,因为你使用列表的第一项来查询列表,并且由于只有3个项目,你只能做array[2],而不是array[3 ] 或更高
标签: java arrays indexoutofboundsexception