线程java.lang.ArrayIndexOutOfBoundsException中的异常:5

时间:2015-01-01 02:36:23

标签: java arrays if-statement while-loop

我是一个试图完成以下教程的新手

    // Create a method called countEvens
    // Return the number of even ints in the given array. 
    // Note: the % "mod" operator computes the remainder, e.g. 5 % 2 is 1. 
/*
 * SAMPLE OUTPUT:
 *  
 * 3
 * 0
 * 2
 *  
 */

以下是我的代码

public static void main(String[] args) {

        int a[] = {2, 1, 2, 3, 4};
         countEvens(a); // -> 3
         int b[] = {2, 2, 0};
         countEvens(b); // -> 3
         int c[] = { 1, 3, 5};
         countEvens(c); // -> 0

    }


    public static void countEvens(int[] x){
        int i = 1;
        int count = 0;
        while ( i <= x.length){
            if (x[i] % 2 == 0){
                count ++;
            }
            i ++;
        }
        System.out.println(count);
    }

代码可以运行,但我收到以下错误消息

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
    at apollo.exercises.ch05_conditionals.Ex5_CountEvens.countEvens(Ex5_CountEvens.java:23)
    at apollo.exercises.ch05_conditionals.Ex5_CountEvens.main(Ex5_CountEvens.java:10)

我可以知道我在这里做错了吗?

4 个答案:

答案 0 :(得分:3)

该行

while ( i <= x.length)

应该是

while ( i < x.length)

例如,如果length的{​​{1}}为5,则索引为0,1,2,3和4.索引从0到1小于数组的长度

然而,最简单的方法是使用a for each循环而不是while循环:

x

答案 1 :(得分:2)

<强>&#39;我&#39;应该从0到length() - 1 ,因为数组索引从0开始,最后一个元素的索引是length() - 1。

因此,您的代码的正确版本将是:

public static void countEvens(int[] x){
    int i = 0;
    int count = 0;
    while ( i < x.length){
        if (x[i] % 2 == 0){
            count ++;
        }
        i ++;
    }
    System.out.println(count);
}

出于特定目的, for循环会更简单。

for(int i = 0; i< x.length(); i++){
  if(x[i]%2==0){
  count++;
  }
}

答案 2 :(得分:1)

while ( i <= x.length),您需要循环,直到i 等于x的长度。数组的最后一个索引始终是 length - 1 ,因此将小于或等于(<=)更改为小于(<)。此外,将i初始化为0,因为Java数组从零开始。

答案 3 :(得分:0)

Java中的数组(以及大多数其他语言)从0开始索引。然而,数组的长度是数组中元素的数量。所以对于你的数组a []

int a[] = {2,1,2,3,4};

指数上升至4,而长度为5.

由于<=(小于等于)运算符,您正在从1到5迭代数组,但是数组的索引是0~4。当您访问数组的每个元素时,您应该使用

if (x[i-1] % 2 == 0) //iterates from 0~4 rather than 1~5

否则你可以设置迭代器int i = 0;并使用小于<运算符来确保迭代器移动0~4