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

标签 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)

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

最佳答案

线

while ( i <= x.length)

应该是

while ( i < x.length)

如果xlength为5,则索引为0、1、2、3、4,索引从0到少1比数组的长度。

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

public static void countEvens(int[] x) {
    int count = 0;
    for (int number : x)
        if (number % 2 == 0)
            count++;
    System.out.println(count);
}

关于java - 线程 java.lang.ArrayIndexOutOfBoundsException : 5 中的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27727924/

相关文章:

java - "generic method""absolute value"java

java - 如何在链表中实现泛型 <E>?

java - 在java中创建具有特定名称的动态对象

mysql - SQLite 和 If() 条件

javascript - 通过 webview 内的 blob 链接下载 pdf

javascript - 如果数组中有数字 1-9,则测试 true 或 false

arrays - 如何在 R 中重新排序数组的第一个维度(不知道总维度)

python - 如何根据两列的最大值拆分数组

python - 循环使用两个计数器

javascript - 如何捕获输入元素的内容并测试它是否是字母 a-z A-Z 之间的字符,并且两个单词之间有空格