Finding out how many of a certain item a player has

Discussion in 'Plugin Development' started by Hoolean, Sep 2, 2012.

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

    Hoolean

    How to find out how many of a certain item a player has? E.g. Find out how many emeralds is in a players inventory.
     
  2. Offline

    DarknessXIII

    Try
    Code:
    event.getPlayer().getItemInHand().getAmount()
    
    or this
    Code:
    event.getPlayer().getInventory().getItem(int)
    
     
  3. Offline

    MrZoraman

    DarknessXIII
    I'm not sure if that is quite what he is looking for because doesn't that only get the amount in that specific slot? I think he wants the total in the entire inventory? I quickly whipped up this method that I think will do the trick.

    Code:
    public int getAmountInInventory(Player player, int itemId)
    {
        int total = 0;
        for(ItemStack is : player.getInventory())
        {
            if(is.getTypeId == itemId)
            {
                total += is.getAmount();
            }
        }
        return total;
    }
    However I cannot promise you that this will work right out of the box. I haven't tested it and because I accidentally put something else on my clipboard, I just typed all that out in the forum code paster thingy manually XD

    I'm pretty sure that foreach loop works, but again, I haven't really tested it so if it doesn't give this a try:
    Code:
    for(ItemStack is : player.getInventory().getContents())
    This is the way I know of that would work. I went through the inventory api, and there doesn't seem to be any methods that return the amount of the item in the ENTIRE inventory. But perhaps I read something wrong. I woke up 10 minutes go lol
     
Thread Status:
Not open for further replies.

Share This Page