【问题标题】:Java: Index out of boundsJava:索引超出范围
【发布时间】:2015-04-12 01:21:52
【问题描述】:

我正在 Greenfoot 为一个学校项目编程,但我不断收到此错误:

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 ++;
                    }
                }
            }
        }
    }      

到目前为止,我似乎无法找到错误,因为我做了一些检查来检查索引。谁能帮我解决这个问题?

【问题讨论】:

  • 如果您的错误出现在您提供的代码中,您知道它一定在这一行:wapenLijst.get(gebruiktWapen).schietKogel(); 使用调试器单步执行您的代码,以查看 wapenLijst 的大小与gebruiktWapen,用于索引 ArrayList。

标签: java indexing arraylist indexoutofboundsexception greenfoot


【解决方案1】:

我将解释错误的原因(假设附加的代码实际上是导致异常的代码),即使问题缺少代码来准确指出如何 em> 它发生了。

java.lang.IndexOutOfBoundsException:索引:1,大小:1

表示您正在访问大小为 1 且索引为 1 的 List。Java 中的索引是从零开始的,因此 Index: 1 表示列表中的第二个元素。没有第二个元素,因此例外。

根据您提供的代码,您只有一个列表,因此错误发生在这里:

wapenLijst.get(gebruiktWapen).schietKogel();

在应用程序的给定状态下,wapenLijst 有一个元素,gebruiktWapen 为 1。根据上面的解释,当只有一个元素时,您尝试访问列表中的第二个元素。

您能否以某种方式实现一些不允许gebruiktWapen 大于wapenLijst.size() 的检查?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-02
    • 1970-01-01
    • 2018-03-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多