Solved Remove 1 Item from a stack

Discussion in 'Plugin Development' started by Dealyise, Jul 9, 2014.

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

    Dealyise

    I got a problem.
    I coded a gun with ammo. When it shoots, it should check the inventory for the ammo.
    If the inventory contains the ammo, it should remove one item.
    But: If I got more than one stack, it removes one item from each stack.
    I dont know atm how I am able to fix this, got a bit confused.
    Any suggestions?
    Source:
    Code:java
    1. ItemStack deagleMunition = null;
    2. for (int i = 0; i < e.getPlayer().getInventory().getContents().length; i++) {
    3. ItemStack stack = e.getPlayer().getInventory().getItem(i);
    4. if (stack == null || stack.getType() != Material.SULPHUR) continue;
    5. deagleMunition = stack;
    6. }
    7.  
    8. if(e.getPlayer().getInventory().contains(deagleMunition)){
    9. for (int i = 0; i < e.getPlayer().getInventory().getContents().length; i++) {
    10. ItemStack stack = e.getPlayer().getInventory().getItem(i);
    11. if (stack == null || stack.getType() != Material.SULPHUR)continue;{
    12. if (stack.getAmount() <= 1)
    13. e.getPlayer().getInventory().setItem(i, null);
    14. else
    15. stack.setAmount(stack.getAmount() - 1);
    16. }
    17.  
    18. }
    19.  
    20. e.getPlayer().updateInventory();
     
  2. Offline

    Gater12

    Dealyise
    The logic of your code clearly says it. You keep looping through the inventory and never told it to stop after finding one stack of gunpowder.

    Also you can use enhanced for-loops to loop through player's contents.
     
  3. Offline

    Necrodoom

    What's the point of "deaglemuniton"? You check if there's an item which matches the ammo, if yes, set it to deagle, repeat till the end of the loop. Then, you check if player has ammo, and then start yet another loop which does the exact same, but also modifies the inventory. The first loop is useless, and you need to break the second loop when ammo removal is successful, instead of continuing to check.
     
  4. Offline

    Dealyise

    Gater12
    How shall I fix that? Any example? I am really confused, because I had some other problems before and now I am really out of concentration atm but I need to fix that first.
    Any point?

    €:
    Got it. Sorry guys, there was a stupid fail, forgot to break the second loop. Thanks!
     
Thread Status:
Not open for further replies.

Share This Page