【发布时间】:2013-12-14 18:17:15
【问题描述】:
我将 0 到 1000 之间的所有数字相加,它们是倍数或 3 和 5。我只是无法将它们相加。我不断收到错误消息:线程“主”java.lang.IndexOutOfBoundsException 中的异常:索引:468,大小: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);
有人知道原因吗?我不明白为什么它不起作用。它打印出数组列表,所以我肯定应该将元素添加在一起......
【问题讨论】:
-
x <= multof3.size()->x < multof3.size() -
附加信息您不需要使用“继续;”当你已经结束循环时