Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 881
Matthew Thibodeau Avatar asked Feb 08 '18 13:02

Matthew Thibodeau


2 Answers

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.

like image 142
Suresh Atta Avatar answered Oct 13 '22 02:10

Suresh Atta


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++;
  }
like image 22
Dheeraj Joshi Avatar answered Oct 13 '22 01:10

Dheeraj Joshi