问题描述
我正在 Greenfoot 为学校项目编程,但我不断收到此错误:
I'm programming in Greenfoot for a school project and I keep getting this error:
java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
at java.util.ArrayList.rangeCheck(ArrayList.java:635)
at java.util.ArrayList.get(ArrayList.java:411)
at Speler.act(Speler.java:60)
at greenfoot.core.Simulation.actActor(Simulation.java:583)
at greenfoot.core.Simulation.runOneLoop(Simulation.java:541)
at greenfoot.core.Simulation.runContent(Simulation.java:215)
at greenfoot.core.Simulation.run(Simulation.java:205)
通过这个代码:
if (Greenfoot.isKeyDown("s"))
{
int wapenID;
if(schietTimer < 1)
{
if(richting != null)
{
if(gebruiktWapen != -1)
{
{
getWorld().addObject(new Kogel(richting), getX(), getY());
schietTimer = 30;
wapenLijst.get(gebruiktWapen).schietKogel();
System.out.println(wapenLijst.size());
if(wapenLijst.get(gebruiktWapen).hoeveelKogels() == 0)
{
gebruiktWapen++;
}
}
}
else
{
if(wapenLijst.size() > 0)
{
gebruiktWapen ++;
}
}
}
}
}
到目前为止,我似乎无法找到错误,因为我做了一些检查来检查索引.有人能帮我解决这个问题吗?
I don't seem to be able to find the error so far since I did some checks to check the index. Can anyone help me out with this?
推荐答案
我会解释错误的原因(假设附加的代码实际上是导致异常的代码),即使问题缺少代码来准确指出如何它发生.
I will explain the reason for the error (given that the attached code is actually the code that causes the exception), even if the question lacks code to exactly pinpoint exactly how it occurs.
java.lang.IndexOutOfBoundsException:索引:1,大小:1
表示您正在访问大小为 1 且索引为 1 的 List
.Java 中的索引是从零开始的,因此 Index: 1 表示列表中的第二个元素.没有第二个元素,因此例外.
means that you are accessing a List
of size 1 with index 1. Indices in Java are zero based, so Index: 1 means the second element in the list. There is no second element, hence the exception.
从你给的代码中你只有一个列表,所以错误发生在这里:
From the code you have given you only have one list, so the error happens here:
wapenLijst.get(gebruiktWapen).schietKogel();
在应用程序的给定状态下,wapenLijst
有一个元素,gebruiktWapen
为 1.根据上面的解释,您尝试访问列表中的第二个元素当只有一个时.
At a given state in your application, wapenLijst
has one element and gebruiktWapen
is 1. As per the explanation above, you try to access the second element in the list when there only is one.
你能否以某种方式实施一些检查,不允许 gebruiktWapen
变得大于 wapenLijst.size()
?
Could you perhaps somehow implement some check that does not allow gebruiktWapen
to become larger than wapenLijst.size()
?
这篇关于Java:索引越界的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!