我是一个正在尝试完成以下教程的新手
// 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)
如果x
的length
为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/