0

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! :)

  • 2
    You are reading the error incorrectly. "Index: 1000, Size: 467" means that you're trying to access the index 1000 of a list that has a size of 467. But since there are no 1000th elemens in a list that has 467 elements, you have an exception ;). – Tunaki May 01 '16 at 12:17
  • Oh okay!! My bad, I didn't know that I was reading it wrongly... In that case how do I ensure that it doesn't read the index beyond the 1000th one? –  May 01 '16 at 12:21
  • Again, you're not reading it correctly. The size of the list is 467. Not 1000. So ensuring that the index doesn't go over 1000 is not the solution. The stack trace tells you the exact line where the exception happens. As yourself the question what is wrong at that line. – JB Nizet May 01 '16 at 12:28

1 Answers1

0

I think that the error is here:

while (n < multiples.size()){
    sum += multiples.get(i);//Here
    System.out.println(sum); 
}

You check if n is less than the size, but you get the number at i, which may or may not be less that the size. You may change it to:

sum += multiples.get(n);
dryairship
  • 6,022
  • 4
  • 28
  • 54