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
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…