ArrayIndexOutOfBoundException同时从JAVA中的数组中分离奇数

我试图想出一个解决方案,只对数组中的奇数进行排序,同时保持偶数不变。为了实现这一点,我尝试将给定数组中的所有奇数删除到一个新数组(odd_arr)中并填充空白,我插入了一个大数字(9731),以便我知道应该在哪里插入奇数一旦这些奇数被排序。


(只是为了理解例:如果数组是 {5,3,2,8,1,4} 那么 step1:odd_arr 将是 {5,3,1} 并且数组是 {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] + " ");

 }

}


慕尼黑的夜晚无繁华
浏览 153回答 2
2回答

慕沐林林

您将for-each循环视为常规循环,for(int i : array){&nbsp; &nbsp; if(array[i] % 2 == 1)应该for(int i :array){&nbsp; &nbsp; if(i % 2 == 1)但是,我实际上会将其分解为几种方法以使其更易于推理。从计算几率的方法开始。喜欢,private static int countOdds(int[] array) {&nbsp; &nbsp; int count = 0;&nbsp; &nbsp; for (int val : array) {&nbsp; &nbsp; &nbsp; &nbsp; if (val % 2 != 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; count++;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return count;}在 Java 8+ 中,也可以这样做private static int countOdds(int[] array) {&nbsp; &nbsp; return (int) Arrays.stream(array).filter(i -> i % 2 != 0).count();}然后,一种将奇数复制到新(临时数组)的方法,例如private static int[] copyOdds(int[] array) {&nbsp; &nbsp; int pos = 0;&nbsp; &nbsp; int[] odds = new int[countOdds(array)];&nbsp; &nbsp; for (int val : array) {&nbsp; &nbsp; &nbsp; &nbsp; if (val % 2 != 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; odds[pos++] = val;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return odds;}或者,在 Java 8+ 中,private static int[] copyOdds(int[] array) {&nbsp; &nbsp; return Arrays.stream(array).filter(i -> i % 2 != 0).toArray();}然后你的sortArray方法实际上是自己写的。首先,复制奇数值。然后对它们进行排序。然后将它们复制回原始数组。喜欢,public static void sortOdds(int[] array) {&nbsp; &nbsp; int[] odds = copyOdds(array);&nbsp; &nbsp; Arrays.sort(odds);&nbsp; &nbsp; int pos = 0;&nbsp; &nbsp; for (int i = 0; i < array.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; if (array[i] % 2 != 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; array[i] = odds[pos++];&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}并且,为了演示,一种main方法public static void main(String[] args) {&nbsp; &nbsp; int[] array = { 5, 3, 2, 8, 1, 4 };&nbsp; &nbsp; System.out.println(Arrays.toString(array));&nbsp; &nbsp; sortOdds(array);&nbsp; &nbsp; System.out.println(Arrays.toString(array));}哪些输出[5, 3, 2, 8, 1, 4][1, 3, 2, 8, 5, 4]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java