for loop and ArrayIndexOutOfBounds

Discussion in 'Plugin Development' started by johnny boy, Jun 27, 2018.

Thread Status:
Not open for further replies.
  1. Offline

    johnny boy

    I have a for loop that goes over an int array with places that my code can place glass panes in my inventory.
    I'm not too sure why I get an ArrayIndexOutOfBounds exception. I know what it means, but I'm still a little puzzled. Do you know why?

    Code:java
    1.  
    2. private int[] glass = {1,2,3,4,5,6,7,8,9,18,27,36,45,54,21,31,41};
    3.  
    4. for (int i = 0; i < glass.length; i++) {
    5.  
    6. System.out.println(glass.length);
    7. System.out.println(i);
    8.  
    9. int invSlot = glass[ i ][I][I][I];
    10.  
    11. // System.out.println(invSlot + "asdkjaskljdlkjasd"); debug line
    12.  
    13. ItemStack glass = new ItemStack(Material.STAINED_GLASS_PANE, 1, (short)3);
    14. inv.setItem(invSlot, glass);
    15. }[/I][/I][/I]
    16.  


    thanks.

    edit: ignore those stupid [ / i ] etc, added by the editor not me :/


     
    Last edited by a moderator: Jun 27, 2018
  2. Offline

    Zombie_Striker

    @MemeplexOwner
    This is most likely what is causing the problem. Remember, Slot IDs start at 0, so the top left corner is 0, the top right is 8, and the bottom right slot is Size minus 1.
     
  3. Offline

    johnny boy

    yes, in the console it said something about 54. Now, I did try to counter this by doing many things. An example is using glass.length -1 instead of glass.length, i think that worked?
     
  4. Offline

    Zombie_Striker

    It shouldn't: 54 will still be encountered at the 14th index, so making it so it does not reach the end (does not reach 41) should not matter.

    What you should do us change 54 to 53, since 54 is out of bounds while 53 is the bottom-right corner for an inventory with 6 rows.
     
  5. Offline

    johnny boy

    Now that I'm reading this in the day, it makes a lot more sense. Thanks
     
Thread Status:
Not open for further replies.

Share This Page