Solved Checking if item is air while iterating through a for loop

Discussion in 'Plugin Development' started by Shadow_tingBRO, Mar 10, 2019.

Thread Status:
Not open for further replies.
  1. I am making a component of my plugin which sells all of a players inventory when they do /sell inv or /sell i. The following code shows what is looked like before when it was not working because I kept getting a null pointer (i got the error on the line profit += getPrice...:

    Code:
    int profit = 0;
             
                int itemsininv = 0;
             
                for(ItemStack item : p.getInventory().getContents()) {
                 
                    p.sendMessage("1");
                    profit += getPrice(item.getType()) * item.getAmount();
    
                    itemsininv++;
                 
    
                 
                }
    I searched around the internet and thought and came up with that it must that Material.AIR was the problem, as there is no amount to air, it must be null.

    So i changed my code to this:

    Code:
    int profit = 0;
             
                int itemsininv = 0;
             
                for(ItemStack item : p.getInventory().getContents()) {
    
                 if(item.getType().equals(Material.AIR))continue;  // continue stops where the code is and goes to the next loop in this for loop (im pretty sure)
                 
                    p.sendMessage("1");
                    profit += getPrice(item.getType()) * item.getAmount();
    
                    itemsininv++;
                 
    
                 
                }
    And I am still getting a null pointer (this time the line where is it if(item.getType().equals(...)), and I have nooooo idea why, any ideas?
     
  2. Offline

    KarimAKL

    @Shadow_tingBRO The ItemStack in the player's inventory isn't material air, it's null, meaning item.getType() is causing a NullPointerException.
     
  3. I did what you advised and I still get a NullPointerException, here is the code:

    Code:
    
    if(item.getType()==null)continue;
    
    
    Is there a way I should be doing this? oh I see its the getType returning null, so how would I check still?
     
    Last edited: Mar 10, 2019
  4. Online

    timtower Administrator Administrator Moderator

  5. omg thnx, how did I not see that!
     
Thread Status:
Not open for further replies.

Share This Page