How to check how many items in an ItemStack

Discussion in 'Plugin Development' started by PQE, Feb 1, 2017.

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

    PQE

    Hey,

    I'm making an AutoSell plugin at the moment, and I ran into an issue when I discovered I didn't know how to check how many items were in an ItemStack. Essentially, the below piece of code, should tell me how much money an inventory is worth (of course this is just for gold ingots atm).

    Code:
    @EventHandler
        public void onBlockBreak(BlockBreakEvent event) {
            Block block = event.getBlock();
            Player player = event.getPlayer();
            PlayerInventory pi = player.getInventory();
            if (pi.firstEmpty() == -1) {
                for (int i = 1; i<=36; i++) {
                    ItemStack item = pi.getItem(i);
                    if (item.getType() == Material.GOLD_INGOT) {
                        for (int z = 1; i<=64; i++) {
                            if (pi.contains(item, z)) {
                                int amountToDeposit = getConfig().getInt("valueOfGold") * z;
                                EconomyResponse er = bankDeposit(player, amountToDeposit);
                               
                            }
                        }
                    }
                }
            }
           
        }
    
    Those last 3 lines all have errors for some reason I can't figure out

    Thanks for the help!
     
  2. Offline

    Drkmaster83

    The ItemStack object has a "getAmount()" method that returns an int (or the stack size), if the ItemStack exists.
    There is also another way to loop through the inventory and "deposit" all the gold, but if you like for-loops, you can stick with this. However, something that is explicitly wrong with your for-loop is that Inventory slots are 0-based. (36 slot inventory's range would be slots 0-35). You can't start at 1 and go all the way up to 36, only slightly under 36 (< 36). Also, I advise to remove the ItemStack in the inventory after depositing it (item.setType(Material.AIR)).

    One more thing: You could and can do this with a non-full inventory, but as you have it right now, it will only work with a full PlayerInventory.
     
Thread Status:
Not open for further replies.

Share This Page