【发布时间】:2016-12-02 13:53:23
【问题描述】:
我正在尝试将数组中的所有数字与 for loop 和 enhanced loop 相加。 for loop 工作正常,但 enhanced loop 返回 out of bounds error。
按照代码:
import java.util.*;
public class test
{
public static void main(String[]args)
{
//This code sums all of the values in an array with a for loop
int count = 0;
int[] array = {1,2,3,4,5,6,7,8,9,10};
for(int item = 0; item<array.length; item++)
{
count += array[item];
}
System.out.println(Arrays.toString(array) + "\nCount = " + count);
//////////////////////////////////////////////////////////////////////////////
//This code is supposed to sum all of the digits in an array with a enhanced loop
int count2 = 0;
int[] array2 = {1,2,3,4,5,6,7,8,9,10};
for(int item : array2)
{
count2 += array2[item];
}
System.out.println(Arrays.toString(array2) + "\nCount = " + count2);
}
}
【问题讨论】:
-
在 java 中,
item代表值,这不像 javascript 中item代表索引。
标签: java arrays for-loop foreach