I'm new to Java programming and was trying to solve some of the Project Euler problems and somehow got stuck on the very first one...
I am trying to find the sum of the multiples of 3 and 5 for a range of numbers from 0 to 1000...
My code is as follows:
import java.util.ArrayList;
public class SumOfMultiplesOf3And5 {
public static void main(String[] args) {
int i = 0;
int sum = 0;
int n = 0;
int totalforthree =0;
int totalforfive = 0;
int totalforall =0;
ArrayList<Integer> multiples = new ArrayList<Integer>();
for (i = 0; i < 1000; i++){
if(i % 3 == 0){
multiples.add(i);
totalforthree += i;
}
else if(i % 5 == 0){
multiples.add(i);
totalforfive += i;
}
}
while (n < multiples.size()){
sum += multiples.get(i);
System.out.println(sum);
}
totalforall = totalforthree + totalforfive;
System.out.println("The sum is: " + totalforall);
}
}
And the error that I get is as follows:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1000, Size: 467
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at SumOfMultiplesOf3And5.main(SumOfMultiplesOf3And5.java:25)
How do I solve this and what is the reason that the exception is thrown despite the size being less than 1000?
My apologies if these questions are too basic but I'm just getting into the programming so I would really appreciate any help I can get!
Thank you very much in advance! :)