For-Each Loop Java Error ArrayIndexOutOfBoundsException

后端 未结 6 1992
感情败类
感情败类 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:30

    Instead of numbers[i] in if (numbers[i] % 2 == 0), just put i.

    The i in your for (int i : numbers) actually stores the elements in the array(numbers) from 0th index up-to the length of the array.

    In if (numbers[i] % 2 == 0), the numbers[i] will give you the element at ith index. And the value of i is some random number from (int)(Math.random() * 51 + 50) which will always gonna be a number greater than 50. So what you're trying to do is accessing some element which is out of bounds of the size of the array that you declared i.e. 8 in int [] numbers = new int[8].

提交回复
热议问题