索引超出for语句的范围

时间:2013-06-18 23:02:16

标签: java arrays

我在运行时遇到错误:“索引数组越界”,我无法找到它。该程序假设取25个随机数,将它们分成偶数和奇数,并显示单独的组。我调试了第一个for语句,很好,它是我的第二个,但我不知道为什么。我可以没有两个相等的数组元素吗?

public class EvensandOdds {



 public static void main(String[] args)  {

    int i;
    int countEven = 0;
    int countOdd = 0;
    int num;
    int numEven = 0;
    int numOdd = 0;
    int [] evenNum;
    int [] oddNum;
    int [] ranNum = new int[25];


    for (i = 0; i <= 24; i++) {
        num = (int) (100 * Math.random());
        ranNum[i] = num;
        if (num % 2 == 0) {
            numEven += 1;
        } else numOdd += 1;
    }

    evenNum = new int[numEven];
    oddNum = new int [numOdd];

    for (i = 0; i <= 24; i++) {
        if (ranNum[i] % 2 == 0) {
            evenNum[countEven] = ranNum[i]; //This separates the two groups into different arrays. Is this a valid statement?
            countEven += 1;
        } else oddNum[countOdd] = ranNum[i];
        countOdd += 1;
    }

    System.out.print("Your even numbers are: \n");
    for (i = 0; i <= countEven; i++) {
        System.out.print(evenNum[i]);
    }

    System.out.print("Your odd numbers are: \n");
    for (i = 0; i <= countOdd; i++) {
        System.out.print(oddNum[i]);
    }



 }
}

3 个答案:

答案 0 :(得分:2)

    对于偶数和奇数执行
  1. countOdd += 1,尝试更改这些行:

    } else oddNum[countOdd] = ranNum[i];
     countOdd += 1;
    

    成:

    } else { 
        oddNum[countOdd] = ranNum[i];
        countOdd += 1; 
    }
    
  2. 更改(正如Lion建议的那样)

    for (i = 0; i <= countEven; i++) {
    

    for (i = 0; i <= countOdd; i++) {
    

    for (i = 0; i < countEven; i++) {
    

    for (i = 0; i < countOdd; i++) {
    

答案 1 :(得分:2)

countOdd += 1;语句不在一对括号内,因此即使数字是偶数也会执行。

} else { 
    oddNum[countOdd] = ranNum[i];
    countOdd += 1; 
}

这可以解决您的错误。

答案 2 :(得分:0)

oddNum数组长度为8 ...但是你使用了更大的countOdd,这会导致异常在线:

oddNum[countOdd] = ranNum[i];

导致此问题的原因是countOdd + = 1;不包含在括号内:

else addNum[countOdd++] = ranNum[i];