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 for loop, i.e. (i = 0; i < numbers.length; i++;), then the code works fine. However, my assignments requires me to use a for-each loop for this particular problem. Am I doing something wrong?
int [] numbers = new int[8];
int even = 0;
int odd = 0;
for (int i = 0; i < numbers.length; i++) {
numbers[i] = (int)(Math.random() * 51 + 50);
}
for (int i : numbers) {
if (numbers[i] % 2 == 0) {
even++;
}
else
odd++;
This throws up the error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 54
if (i % 2 == 0) {is enough. Here,iis the item in your array, not the index.