6

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
3
  • 1
    You're already picking each item with the for-each loop, so if (i % 2 == 0) { is enough. Here, i is the item in your array, not the index. Commented Feb 8, 2018 at 13:39
  • In the second loop the varieble i means exact value not index Commented Feb 8, 2018 at 13:43
  • that's a very basic mistake from you man! Commented Feb 8, 2018 at 14:12

6 Answers 6

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

Sign up to request clarification or add additional context in comments.

5 Comments

So in a for-each loop, it actually references the value rather than just the location in the array?
@MatthewThibodeauSo when you were using numbers[i], if your element had a value of 2500, you were refering to numbers[2500]
don't you think this is the same answer as above by Dheeraj Joshi. I don't see a value in putting same answers twice.
@AdeshKumar I have not duplicated. You should have checked the timestamps of the answers. I am the first answerer as far as I know.
oh! so it's otherwise. Sorry my bad! Neverthless the answer above should go away then.
6

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

Comments

2

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

Comments

1

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

Comments

0

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

Comments

0

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;

2 Comments

Though +1 for using reducer nicely and the logic to get odds without any much calculation. Though you should try to use Int stream to create the Array as well.
I think the focus of this question is to get evens and odds count. I will edit my answer after working on that

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.