Don't see the problem with my code

Discussion in 'Plugin Development' started by RAFFYN, Aug 23, 2021.

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

    RAFFYN

    Hello,

    I wanted to get the contents of a player inventory and the amount of this specific item but for some reason my ItemStack in the for loop is always null

    Code:
    Player p = (Player) sender;
                Material playerMainHand = p.getInventory().getItemInMainHand().getType();
    
    int i = 0;
                ItemStack[] playerInventory = p.getInventory().getContents();
                for (ItemStack is : playerInventory) {
                    if (is.getType().equals(playerMainHand)) {
                        i = i + is.getAmount();
                    }
                }
    Please help
    ty
     
  2. Offline

    Strahan

    Player inventory can contain null items, and you aren't null checking. You should have it like:
    Code:
    ItemStack[] playerInventory = p.getInventory().getContents();
    for (ItemStack is : playerInventory) {
      if (is == null) continue;
    
      if (is.getType().equals(playerMainHand)) {
        i = i + is.getAmount();
      }
    }
    Well, what I'd actually do is:
    Code:
    for (ItemStack is : p.getInventory().getContents()) {
      if (is == null) continue;
      if (!is.getType().equals(playerMainHand)) continue;
    
      i += is.getAmount();
    }
     
Thread Status:
Not open for further replies.

Share This Page