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 (numbers[i] % 2 == 0) {
Inside your foreach loop, you need not to access it with index. Just i
is enough as foreach keep on gives you the element
directly (not the index) inside the array/collection you are using.
if (i % 2 == 0) {
for (int i : numbers) {
if (i % 2 == 0) {
even++;
}
else{
odd++;
}
}
You can actually shorten your codes by eliminating the second loop completely by checking the even or odd in first loop itself.
For each loop in your case will be explained like:
for (int i : numbers) {
every integer in array numbers will be placed in i
one by one
so,what you are doing wrong is:
if (numbers[i] % 2 == 0) {
for (int i : numbers) {
if (numbers[i] % 2 == 0) {
even++;
}
else {
odd++;
}
i
will not be increasing evrytime loop proceed like in the traditional for loop, here i
carry the actual value
so you should change from numbers[i]%2==0
to just i%2==0
for (int i : numbers) {
if (i % 2 == 0) {
even++;
}
else {
odd++;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With