1

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)

By this code:

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?

  • If your error is occurring in the code you have provided, you know it must be in this line: `wapenLijst.get(gebruiktWapen).schietKogel();` Step through your code with a debugger to see the size of wapenLijst vs. the value of gebruiktWapen, which you are using to index your ArrayList. – mstbaum Feb 11 '15 at 15:44

1 Answers1

1

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: Index: 1, Size: 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();

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.

Could you perhaps somehow implement some check that does not allow gebruiktWapen to become larger than wapenLijst.size()?

Magnilex
  • 11,584
  • 9
  • 62
  • 84