我正在将 0 到 1000 之间的所有数字相加,这些数字是 3 和 5 的倍数。我只是无法将它们相加。我不断收到错误消息: Exception in thread "main"java.lang.IndexOutOfBoundsException: Index: 468, Size: 468
我的代码
//Multiple of 3 and 5 up to 1000
int total = 0;
int answer = 0;
ArrayList<Integer> multof3 = new ArrayList<Integer>();
for(int i =0; i <=1000; i++){
if(i % 3 == 0 || i % 5==0){
multof3.add(i);
total++;
}else{
continue;
}
}
System.out.println(multof3);
System.out.println(total);
//looping through array to get sum of elements
for(int x =0; x <= multof3.size(); x++){
answer= answer + multof3.get(x);
}
System.out.println(answer);
有谁知道原因吗?我不明白为什么它不起作用。它打印出数组列表,所以我肯定应该将元素添加在一起......
最佳答案
循环数组时,您必须记住它是从 0 开始索引的。
for(int x =0; x < multof3.size(); x++){
answer= answer + multof3.get(x);
}
如果列表中有 468 个项目,则 size() 将返回 468,但最后一个项目位于索引 467。使用增强的 for 循环可以帮助避免此类问题:
for(Integer i: multof3){
answer += i;
}
关于java - 尝试添加数组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20586645/