Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
940 views
in Technique[技术] by (71.8m points)

arrays - 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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...