1

I need to find out if a player has a certain item in their inventory. I tried to find it in the documentation, but it is so terrible (as for me) that I could not find it. So far, there is such a code that works, but it works when a player places or breaks a block with the item I need, and I need it to be constantly tracked. For example, I wrote a command and it turned out that there is such an object, or not.

@EventHandler
public  void yes(PlayerInteractEvent e){
    Player player = e.getPlayer();
    ItemStack item = e.getItem();
    if(item.getType() == Material.DIAMOND_ORE){
        player.sendMessage("Yes");
    }else{
        player.sendMessage("No");
    }
}
pppery
  • 3,731
  • 22
  • 33
  • 46
Venom
  • 47
  • 5

1 Answers1

2

Minecraft Java Inventory Task

There I have a solution. The first code snippet is for checking if an item is in inventory without quantity.

The Code:

@EventHandler
public void checkInventory(InventoryClickEvent e) {
    if (e.getWhoClicked() instanceof Player) {
        Player player = (Player) e.getWhoClicked();
        ItemStack item = new ItemStack(Material.DIAMOND_ORE);

        if (player.getInventory().contains(item)) {
            player.sendMessage("Yes");
        } else {
            player.sendMessage("No");
        }
    }
}

Here you also have a method where you can check with quantity.

The Code:

@EventHandler
public void checkInventory(InventoryClickEvent e) {
    if (e.getWhoClicked() instanceof Player) {
        Player player = (Player) e.getWhoClicked();
        ItemStack item = new ItemStack(Material.DIAMOND_ORE);
        int desiredQuantity = 2;
        int itemCount = 0;

        for (ItemStack stack : player.getInventory().getContents()) {
            if (stack != null && stack.isSimilar(item)) {
                itemCount += stack.getAmount();
            }
        }

        if (itemCount >= desiredQuantity) {
            player.sendMessage("Yes");
        } else {
            player.sendMessage("No");
        }
    }
}
AztecCodes
  • 1,130
  • 7
  • 23
  • Thank you. Only now, when I add in contains(item, 2), that is, this number of the item, it says "No" to me. Although there are exactly 2 diamond ore in the inventory. Or is something else used in this case? – Venom Jun 26 '23 at 12:49
  • @Venom I edited my answer with a second method that also can do quantity checks. – AztecCodes Jun 26 '23 at 13:07
  • Thank you very much, it works It seems there were some methods that check the amount of .getAmount () like. He didn't fit the situation* – Venom Jun 26 '23 at 13:12