I'm trying to add up the elements in the array with an enhanced for loop. If I do it with a normal for loop, it works. But when I'm using an enhanced for loop it throws an IndexOutOfBounds exception and I'm not sure why that's happening?
int[ ] array = {1,2,3};
int total = 0;
for(int counter : array) {
total = total + array[counter];
}
System.out.println(total);
counter is not index, its the element. You need to add the counter to total.
If you are using Java 8 then you can simplify it to:
int[ ] array = {1,2,3};
System.out.println(Arrays.stream(array).sum());
If you would still like to do it without streams:
int[ ] array = {1,2,3};
int total = 0;
for(int counter : array) {
total = total + counter;
}
System.out.println(total);
As Aniket previoysly said, counter is not an index.
Your code is a shorter version of this code:
for (int i = 0; i<array.size; i++){
counter = array[i];
total = total + counter;
}
As you can see, counter becomes the element of array[i] and i is the index of the array.
If you wanted to keep track of the index using your version of the code, you would have to create an outside variable called i = 0 and increment it by one each repetition.
int i = 0
for (counter : array){
i++;
counter = array[i];
total = total + counter;
}
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