Matthew Thibodeau
Matthew Thibodeau

Reputation: 161

For-Each Loop Java Error ArrayIndexOutOfBoundsException

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

Upvotes: 6

Views: 3006

Answers (6)

Debu Shinobi
Debu Shinobi

Reputation: 2582

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].

Upvotes: 1

Dheeraj Joshi
Dheeraj Joshi

Reputation: 1582

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++;
  }

Upvotes: 6

Vinay Prajapati
Vinay Prajapati

Reputation: 7504

Though there are lot many answers. You could achieve same by using java-8 streams as well. Use reducer to find out the even's count and then from length reduce the even's count to get odd's count.

See code below:-

   int[] numbers = new int[8];

    for (int i = 0; i < numbers.length; i++) {
        numbers[i] = (int) (Math.random() * 51 + 50);
    }

    int even = Arrays.stream(numbers)
            .reduce(0, (a, b) -> {
                a += b % 2 == 0 ? 1 : 0;
                return a;
            });
    int odd = numbers.length - even;

Upvotes: 0

Suresh Atta
Suresh Atta

Reputation: 121998

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.

Upvotes: 7

UmaShankar Chaurasiya
UmaShankar Chaurasiya

Reputation: 111

In for Each loop no need to provide numbers[i] so use the following code.
for (int i : numbers) , int i is number present in array. so just put the condition on number itself. If u are using number[i] then it will check the value of i th index , and if any number is greater then your array size it will throw ArrayOutOfBox Exception.

 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 (i % 2 == 0) {
                even++;
            }
            else
                odd++;

Upvotes: 0

Roee Gavirel
Roee Gavirel

Reputation: 19443

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++;
    }
}

Upvotes: 2

Related Questions