Hey guys, I’m currently working on adding items to an inventory (which is an arraylist) and making them display when I go to bring up my inventory, heres the code that I have for it so far.
This is in my “InventoryState” class
for(ItemEntity p: Player.playerInventory){
if(Player.playerInventory.get(0) != null) //my problem is in this for statement somehow
g.drawImage(p.getSprite(),50,50,this);
if(Player.playerInventory.get(1) != null) //if i take out this "if statment" than I'm able to display the 1st item fine.
g.drawImage(p.getSprite(),100,100,this);}
This is in my “Player” class
public static ArrayList<ItemEntity> playerInventory = new ArrayList <ItemEntity>(16);
if(GameLoop.keysPressed[69]==true){ // picks up an item and adds it to the player inventory
for(Entity p : GamePlayState.entities){
if (p instanceof ItemEntity){
if(xCord-p.getX()<15&&yCord-p.getY()<15&&xCord-p.getX()>-15&&yCord-p.getY()>-15){
playerInventory.add((ItemEntity) p);
p.Hit(p,Entity.HitEnum.pickup,0);}}}}
if(GameLoop.keysDown[73] == true)//opens inventory state
StateStack.pushState("InventoryState");
Ok so, if I go in my game and pick up 2 or more items with the code I have above and then switch to my inventory state than everything will display as expected, but if I were to pick up just 1 item and switch to my inventory than I get an ArrayOutOfBounds Exception.
If I were to remove the 2nd “if statement” so it would just be.
for(ItemEntity p: Player.playerInventory){
if(Player.playerInventory.get(0) != null)
g.drawImage(p.getSprite(),50,50,this);}
Than the 1 item displays properly in the inventory without an exception. I really feel like its somthing very simple thats going on here, but after messing with it for awhile I cant seem to pinpoint how to work with this. Any help would be greatly appreciated (: