我正在尝试使用增强的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)
counter不是索引,它的元素.你需要添加counter到total.
如果您使用的是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)
| 归档时间: |
|
| 查看次数: |
81 次 |
| 最近记录: |