gpt4 book ai didi

java - 线程中的异常 "main"java.lang.IndexOutOfBoundsException : Index: 15, 大小:5

转载 作者:行者123 更新时间:2023-12-01 18:21:31 25 4
gpt4 key购买 nike

嗨,我正在尝试解决 euler 项目中的第一个问题,该问题要求 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)

我已经搜索过这个错误,但仍然无法使其工作。

最佳答案

它发现您的循环时间超过了数组列表的大小。
您必须使用 i < multiples.size(); 而不是 i <= 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;

}

关于java - 线程中的异常 "main"java.lang.IndexOutOfBoundsException : Index: 15, 大小:5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27631088/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com