增强的For循环不会在数组中添加元素

Neo*_*Neo 2 java java-8

我正在尝试使用增强的for循环来添加数组中的元素.如果我使用正常的for循环,它可以工作.但是,当我使用增强的for循环时,它会引发IndexOutOfBounds异常,我不确定为什么会发生这种情况?

int[ ] array = {1,2,3};
int total = 0; 
for(int counter : array) {
    total = total + array[counter];
}
System.out.println(total);
Run Code Online (Sandbox Code Playgroud)

Ani*_*wat 6

counter不是索引,它的元素.你需要添加countertotal.

如果您使用的是Java 8,则可以将其简化为:

int[ ] array = {1,2,3};
System.out.println(Arrays.stream(array).sum());
Run Code Online (Sandbox Code Playgroud)

如果你仍然想在没有流的情况下这样做:

int[ ] array = {1,2,3};
int total = 0; 
for(int counter : array) {
    total = total + counter;
}
System.out.println(total);
Run Code Online (Sandbox Code Playgroud)