Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/333.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
线程java.lang.ArrayIndexOutOfBoundsException中的异常:5_Java_Arrays_If Statement_While Loop - Fatal编程技术网

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

线程java.lang.ArrayIndexOutOfBoundsException中的异常:5,java,arrays,if-statement,while-loop,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 * */ 下面是我

我是一个新手,正在尝试完成下面的教程

    // 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);
    }
我能知道我在这里做错了什么吗?

时(我排队时)

while ( i <= x.length)
Java(和大多数其他语言)中的数组从0开始被索引。但是数组的长度是数组中元素的计数。因此对于数组a[]

int a[] = {2,1,2,3,4};
索引增加到4,而长度为5


由于“i”应该从0到length()-1,因为数组索引从0开始,最后一个元素的索引是length()-1,所以从1到5迭代数组,因此出现索引越界错误

因此,代码的正确版本应为:

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);
}
publicstaticvoidcountevens(int[]x){
int i=0;
整数计数=0;
而(i
对于您的特定用途,For循环会更简单。

for(int i = 0; i< x.length(); i++){
  if(x[i]%2==0){
  count++;
  }
}
for(int i=0;i
问题不是在数组上迭代太多次,而是数组是基于零的,OP假设1 basedIt实际上是。用
i-1
覆盖它是一个糟糕的解决方案。实际上不是。OP迭代了5次,但是1~5次,而不是0~4次。不是太多次,但位置错误。我同意i-1不漂亮,b但这是最快的解决方案。但你是对的。从0开始,迭代到iint a[] = {2,1,2,3,4};
if (x[i-1] % 2 == 0) //iterates from 0~4 rather than 1~5
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(int i = 0; i< x.length(); i++){
  if(x[i]%2==0){
  count++;
  }
}