How to count items with same enchantment?

Discussion in 'Plugin Development' started by lucasdidur, Mar 16, 2013.

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

    lucasdidur

    Hello,

    I'm trying to count items with same enchantments, but the code is not work, could someone help to get this code working?

    Code:
        public static Integer getItemCount(ItemStack item, ItemStack[] items)
        {
            Material material = item.getType();
            
            int count = 0;
            for (int i = 0; i < items.length; i++)
            {
                if(items[i] != null && items[i].getType().equals(material) && items[i].getDurability() == 0 && items[i].getEnchantments().size() == 0)
                {
                    if(item.getEnchantments() != null)
                    {
                        for(Enchantment e : item.getEnchantments().keySet())
                        {
                            if(!items[i].getItemMeta().hasEnchant(e))
                            {
                                continue;
                            }
                        }
                    }
                    
                    count += items[i].getAmount();
                }
            }
            
            return count;
        }
    
     
  2. Offline

    Nitnelave

    The problem is that the continue in the center applies to the innermost for loop, so the enchantment. What you could do is create another method bool hasEnchantment (Itemstack item, List<Enchantment> (or something like that) list), and then your code would look like
    Code:
    int count = 0;
    for (int i = 0; i < items.length; i++)
      if (hasEnchantment (items[i], item.getEnchantments ())
        count ++;
    return count;
     
  3. Offline

    Barinade

    int count = 0;
    List<Enchantment> enchantments = new ArrayList<Enchantment>();
    for (Map.Entry<Enchantment, Integer> me : item.getEnchantments()) {
    enchantments.add(me.getKey());
    }
    for (ItemStack is : items) {
    for (Map.Entry<Enchantment, Integer> me : is.getEnchantments() {
    if (enchantments.contains(me.getKey()) {
    count++;
    }
    }
    }
    //count = items in inventory with a similar enchantment as the target item

    This was written in the forum reply box by an extremely tired person, there are probably some errors.
     
Thread Status:
Not open for further replies.

Share This Page