【问题标题】:ArrayIndexOutOfBoundException while separating odd numbers from an Array in JAVA [duplicate]在JAVA中从数组中分离奇数时出现ArrayIndexOutOfBoundException [重复]
【发布时间】: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 &lt; array.size(); ++i)。查看this section in the Java Tutorials 了解其中的区别。
  • 它不起作用,因为您使用增强的 for 循环(它返回数组的项目,不是索引)并使用返回的项目从名单。如果你的列表包含3, 6, 123,它会在第一个崩溃,因为你使用列表的第一项来查询列表,并且由于只有3个项目,你只能做array[2],而不是array[3 ] 或更高

标签: java arrays indexoutofboundsexception


【解决方案1】:

您将for-each 循环视为常规循环,

for(int i : array){
    if(array[i] % 2 == 1)

应该是

for(int i :array){
    if(i % 2 == 1)

但是,我实际上会将其分解为几种方法,以便于推理。从计算几率的方法开始。喜欢,

private static int countOdds(int[] array) {
    int count = 0;
    for (int val : array) {
        if (val % 2 != 0) {
            count++;
        }
    }
    return count;
}

在 Java 8+ 中也可以这样做

private static int countOdds(int[] array) {
    return (int) Arrays.stream(array).filter(i -> i % 2 != 0).count();
}

然后,一种将奇数复制到新的(临时数组)的方法,例如

private static int[] copyOdds(int[] array) {
    int pos = 0;
    int[] odds = new int[countOdds(array)];
    for (int val : array) {
        if (val % 2 != 0) {
            odds[pos++] = val;
        }
    }
    return odds;
}

或者,在 Java 8+ 中,

private static int[] copyOdds(int[] array) {
    return Arrays.stream(array).filter(i -> i % 2 != 0).toArray();
}

然后您的sortArray 方法实际上会自行编写。首先,复制奇数值。然后对它们进行排序。然后将它们复制回原始数组。喜欢,

public static void sortOdds(int[] array) {
    int[] odds = copyOdds(array);
    Arrays.sort(odds);
    int pos = 0;
    for (int i = 0; i < array.length; i++) {
        if (array[i] % 2 != 0) {
            array[i] = odds[pos++];
        }
    }
}

并且,为了演示,main 方法

public static void main(String[] args) {
    int[] array = { 5, 3, 2, 8, 1, 4 };
    System.out.println(Arrays.toString(array));
    sortOdds(array);
    System.out.println(Arrays.toString(array));
}

哪些输出

[5, 3, 2, 8, 1, 4]
[1, 3, 2, 8, 5, 4]

【讨论】:

    【解决方案2】:

    首先,尽量使用正确的缩进,这样更容易阅读。

    使用时:

    for (int i : array) {}
    

    变量“i”将是数组中的下一个,所以第一次是 5,然后是 3,依此类推。有一次它将是 8,当您尝试在长度为 6 的数组上调用 array[8] 时,它将返回您的错误。

    而不是你正在做的,你应该使用:

    class Test {
    
    public static int[] sortArray(int[] array) {
    
    int[] odd_arr = new int[50];
    int k =0;
    
    
    for(int i = 0; i < array.length; i++){
      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 = 0; i < array.length; i++) {
      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] + " ");
     }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-23
      • 1970-01-01
      • 2020-07-12
      • 1970-01-01
      • 1970-01-01
      • 2017-09-04
      相关资源
      最近更新 更多