for loop and ArrayIndexOutOfBounds

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

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


    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?

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


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

    Last edited: Jun 27, 2018
  2. Offline


    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


    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


    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


    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