我是一个新手,正在努力完成下面的教程
// 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)我能知道我做错了什么吗?
发布于 2015-01-01 02:37:59
在while ( i <= x.length)中,一直循环到i等于x的长度为止。数组的最后一个索引总是长度- 1,因此将小于或等于(<=)更改为仅小于(<)。另外,将i初始化为0,因为Java数组是基于零的.
发布于 2015-01-01 02:42:43
线
while ( i <= x.length)应该是
while ( i < x.length)例如,如果length of x为5,则索引为0、1、2、3和4。索引从0增加到比数组长度少1。
然而,最简单的方法是使用for每个循环而不是while循环:
public static void countEvens(int[] x) {
int count = 0;
for (int number : x)
if (number % 2 == 0)
count++;
System.out.println(count);
}发布于 2015-01-01 02:45:52
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。
https://stackoverflow.com/questions/27727924
复制相似问题