这是我的代码:
import java.util.ArrayList;
public class PostmanProblem {
public static void main(String[] args) {
//Make the ArrayList and fill it
ArrayList<Door> al = new ArrayList<Door>();
for(int i = 0; i<=9; i++){
al.add(new Door("closed", i));
}
//Do the problem
for (int i = 1; i < 100; i++){
for (int n = i; n < 100; n+=i){
if (al.get(n).isClosed()){
al.get(n).open();
}
else
{
al.get(n).close();
}
}
}
for(Door d : al){
System.out.print(d.toString() + "\t");
}
}
}
我不知道为什么,但我收到以下异常:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 10, Size: 10
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at PostmanProblem.main(PostmanProblem.java:15)
它引用的行是嵌套 for 循环中 if 语句的开头。 Door 类具有返回 boolean 值的 isClosed() 方法和返回 boolean 值的 isOpen() 方法。它具有 void 函数 open() 和 close(),可将其状态更改为打开或关闭。 Door 的构造函数是 Door(String state, int id)。希望这就是您所需要的。提前致谢!
最佳答案
事情是这样的:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 10, Size: 10
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at PostmanProblem.main(PostmanProblem.java:15)
这为您提供了大量信息。
PostmanProblem.java
第 15 行。那里发生了什么事?-
java.util.ArrayList.get
,.get
有问题您在ArrayList
上调用的方法. -
java.lang.IndexOutOfBoundsException: Index: 10, Size: 10
这是大量信息,它使问题变得非常容易解决。
首先,转到发生错误的行。查看您尝试访问的索引。根据程序实际应该执行的操作,您是否访问了正确的索引?或者你在这里犯了逻辑错误?您应该能够访问该数组的索引以实现程序预期执行的操作,这是否有意义?
如果不应访问该索引,那么您的错误就在这里。您需要修复控制正在访问的索引的逻辑。但是,如果这是一个应该能够访问的索引,那么问题是您没有创建 ArrayList
足够大。所以现在您需要转到设置 ArrayList
的代码部分。并找出你在这里犯了什么逻辑错误以及为什么你的 ArrayList
没有你想要的那么大。
for(int i = 0; i<=9; i++){
al.add(new Door("closed", i));
}
您可以在此处将值加载到 al
中。您输入了十个值。它们位于索引 0
处。通过9
.
for (int i = 1; i <= 100; i++){
for (int n = i; n <= 100; n+=i){
if (al.get(n).isClosed()){
al.get(n).open();
} else {
al.get(n).close();
}
}
}
这就是你要出界的地方。您正在尝试进入索引 10(以及更多),但最大的索引是 9。
关于Java IndexOutOfBoundsException 抛出,不确定原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20414793/