Counting an item in a players inventory

Discussion in 'Plugin Development' started by MarkusK96, Mar 4, 2015.

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

    MarkusK96

    Code:
    for (ItemStack is : sender.getInventory()
                            .all(new ItemStack(mat, 1, damage)).values()) {
                        amount = amount + is.getAmount();
    }
    
    I tried this but it did not work, amount is always 0.

    "mat" is a Material and "damage" is "damage" in ItemStack.

    E.g.: If "mat" is "Material.STONE" and "damage" is "1" it should count granite.
     
    Last edited: Mar 5, 2015
  2. That's because ItemStack parameters are (Material, int, short)
    At the moment you're inputting the damage as the amount of the item, not the data value. It should be: new ItemStack(mat, 1, damage)

    This may work with all(), not sure.
     
    MarkusK96 likes this.
  3. Offline

    MarkusK96

    Thank you!

    But if I use new ItemStack(mat, 1, damage) it does only count stacks with exactly one item.

    Found a solution:
    Code:
    int amount=0;
    for (ItemStack is : sender.getInventory().all(mat).values()) {  //gets all Stacks with the specific Material
        if (is.getDurability() == damage) {                          //checks, if the damage is correct
            amount = amount + is.getAmount();                      //adds the amount of the stack to the counter amount
        }
    }
    
    Thanks again, stupid reading mistake...

    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited by a moderator: Jun 13, 2016
  4. Just saying, if you want your code to look neater you can do: amount += is.getAmount();
     
Thread Status:
Not open for further replies.

Share This Page