For-Each Loop Java Error ArrayIndexOutOfBoundsException

后端 未结 6 1991
感情败类
感情败类 2020-12-10 07:51

In my program I need a for-each loop which counts the number of evens in the given array and increments the variable even for each one. When I use a standard

6条回答
  •  情深已故
    2020-12-10 08:37

    The i is the number itself, not the index. so you should:

    for (int i : numbers) {
        if (i % 2 == 0) { // <-- use i not numbers[i]
            even++;
        }
        else {
            odd++;
        }
    }
    

提交回复
热议问题