线程" main"中的例外情况java.lang.IndexOutOfBoundsException:索引:15,大小:5

时间:2014-12-24 03:31:23

标签: java arraylist

您好我试图在项目欧拉中提出第一个问题      1000以下的3或5的倍数之和。这是我做过的代码。

import java.util.ArrayList;

public class MultiplesOf3And5 {

    public static void main(String[] args)
    {
        int x = 0; // multiples of 3
        int y = 0; // multiples of 5
        int sum = 0; // sum of the multiples of 3 or 5
        int quotient3; //check for the remainder of numbers that are multiples of 3
        int quotient5; //check for the reaminder of numbers that are multiples of 5

        ArrayList<Integer> multiples = new ArrayList<Integer>();

        while ( x <= 999 && y <= 1000)
        {

            quotient3 = x % 3; // check remainder 
            quotient5 = y % 5; // check reaminder

            if (quotient3 == 0 && quotient5 == 0) // check if both x and y are multiples of 3 and 5
            {
                multiples.add(x); // if true put it in a arraylist
            }

            if (quotient3 == 0) // checks if x is a multiples of 3 
            {
                if (multiples.contains(x)) // check if x is already in the arraylist 
                {
                    EmptyStatement:;
                }
                else {
                    multiples.add(x); // add x in the arraylist 
                }
            }

            if (quotient5 == 0)
            {
                if (multiples.contains(y))
                {
                    EmptyStatement:;
                }
                else {
                    multiples.add(y);
                }
            }

            x+=3;
            y+=5;

        }

        for (int i = 0; i <= multiples.size(); i++) // loop into the arraylist and get the sum of the elements
        {
            int value = (int) multiples.get(i);
            sum = sum + value;
        }
        System.out.print(sum);
    }
}

修复了一些编译器错误后,我设法编译它。但是一旦我运行它,我就会出现错误,

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 15, Size: 5
at java.util.ArrayList.rangeCheckForAdd(Unknown Source)
at java.util.ArrayList.add(Unknown Source)
at MultiplesOf3And5.main<MultiplesOf3And5.java:23)

我已经搜索过这个错误,但我还是无法让它发挥作用。

3 个答案:

答案 0 :(得分:3)

你看到你的循环时间超过你的arraylist大小 你必须使用 i&lt; multiples.size(); 而不是 i&lt; = multiples.size();

所以,替换你的代码:

for (int i = 0; i <= multiples.size(); i++) 
// loop into the arraylist and get the sum of the elements
        {
        int value = (int) multiples.get(i); 
        sum = sum + value;
        }

使用:

for (int i = 0; i < multiples.size(); i++) 
// loop into the arraylist and get the sum of the elements
        {
        int value = (int) multiples.get(i); 
        sum = sum + value;

        }

答案 1 :(得分:1)

arrayList基于零,所以如果arraylist.size = 400那么你的最高索引是399。 循环应该使用less than (<)而不是less than or equal to (<=)

答案 2 :(得分:0)

使用

怎么样?
for(int i : multiples){

sum += i ;

}

更简单,这种陈述至少不会遇到任何溢出。