Trying to count items...

Discussion in 'Plugin Development' started by willeb96, Nov 24, 2012.

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

    willeb96

    Hey guys :)
    What am I doing wrong here?

    PHP:
    public class Items {
        public static 
    int countItems(Player playerMaterial materialshort damageValue) {
            
    PlayerInventory inventory player.getInventory();
            
    ItemStack[] items inventory.getContents();
            
    int amount 0;
            for (
    int i=0i<items.lengthi++) {
                if (
    items[i].getType() == material && items[i].getDurability() == damageValue) {
                    
    amount += items[i].getAmount();
                }
            }
            return 
    amount;
        }
    }
    NullPointerException at the if-statement.

    Thanks!

    Also, this is where I call the method.
    PHP:
    ItemStack items = new ItemStack(Material.OBSIDIAN64);
    if (
    Items.countItems(playeritems.getType(), items.getDurability()) >= items.getAmount()) {
    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited by a moderator: May 30, 2016
  2. Offline

    fireblast709

    empty slots are null
     
  3. Offline

    willeb96

    Shouldn't items[i].getType() == material just return false then?
    If not, what would the best way solving this be?
     
  4. Offline

    fireblast709

    no, you cannot call .getType() on null (thats why it is throwing a NPE :p)
    Code:java
    1. public class Items
    2. {
    3. public static int countItems(Player player, Material material, short damageValue)
    4. {
    5. PlayerInventory inventory = player.getInventory();
    6. ItemStack[] items = inventory.getContents();
    7. int amount = 0;
    8. for (ItemStack item : items)
    9. {
    10. if (item.getType() == material && item.getDurability() == damageValue) {
    11. amount += item.getAmount();
    12. }
    13. }
    14. return amount;
    15. }
    16. }

    a foreach loop should not loop the null values
     
  5. Offline

    willeb96

    Ok, thanks for the help :D
     
Thread Status:
Not open for further replies.

Share This Page