Reputation: 339
Im adding all the numbers between 0 and 1000 which are multiples or 3 and 5. Im just having trouble adding them up. I keep on getting the error message: Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 468, Size: 468
My Code
//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);
Anyone know the reason why? I cant understand why its not working. It prints out the arraylist so surely I should add the elements together...
Upvotes: 2
Views: 90
Reputation: 1079
which uses just <
instead of <=
:
for(int x =0; x < multof3.size(); x++){
answer= answer + multof3.get(x);
}
Upvotes: 0
Reputation: 2432
You're trying to access the element beyond the final one in the ArrayList. Change
for(int x =0; x <= multof3.size(); x++){
to
for(int x =0; x < multof3.size(); x++){
Upvotes: 0
Reputation: 34146
Change the for
condition <=
to <
:
for (int x = 0; x < multof3.size(); x++) {
answer = answer + multof3.get(x);
}
Remember index starts in 0.
Upvotes: 0
Reputation: 103135
When looping through an array you have to keep in mind that it is indexed from 0.
for(int x =0; x < multof3.size(); x++){
answer= answer + multof3.get(x);
}
If there are 468 items in the list then size() will return 468 but the last item is at index 467. Using the enhanced for loop can help avoid this type of problem:
for(Integer i: multof3){
answer += i;
}
Upvotes: 3