Checking if there is room in a players inventory for an item

Discussion in 'Plugin Development' started by Scullyking, Jul 22, 2014.

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

    Scullyking

    My method for getting whether a players inventory has room for an item.
    It throws a NPE on line 7.

    (reason I'm checking display names is incase I have a custom item)

    Code:java
    1. public static boolean isItemTakeable(Player player, ItemStack item){
    2.  
    3. ItemStack[] contents = player.getInventory().getContents();
    4.  
    5. for (int i = 0; i < contents.length; i++){
    6.  
    7. if (contents[i].getType().equals(item.getType())){
    8. if (!contents[i].getType().equals(Material.AIR)){
    9. if (contents[i].getItemMeta().getDisplayName().equals(item.getItemMeta().getDisplayName())){
    10. if (!(contents[i].getAmount() == contents[i].getMaxStackSize())){
    11. return true;
    12. }
    13. }
    14. }
    15.  
    16. }
    17.  
    18. if (contents[i].getType().equals(Material.AIR)){
    19. return true;
    20. }
    21. }
    22. return false;
    23. }[/i][/i][/i][/i][/i][/i]



    please ignore the tags which are being inserted by all the calls in the code...
    Thanks
     
  2. Offline

    JRL1004

    Scullyking Instead of "if (!contents.getType().equals(Material.AIR))" try "if (!contents == null))"
     
  3. Offline

    Scullyking

    JRL1004

    My bad the error was on line 7 not 9. Your suggestion gives same error.
     
  4. Offline

    stormneo7

    A better way to do this is
    Code:java
    1. if(p.getInventory().firstEmpty() == (-1)){
    2. // No Room
    3. }else{
    4. // There Is Room
    5. }

    If the inventory's full, .firstEmpty() will return -1 as, obviously, the inventory's full.
    Otherwise, it'll return the inventory's first available slot.

    As for your code, there will obviously be errors. ItemStack[] will have null slots in them.
    You cannot do null.getType() as, well... you figure that out.
    Your first check should be
    Code:
    if (contents[i] != null) {
    }
    Hope this has helped. Tag me if you have any questions.
     
  5. Offline

    rippin

    It returns null because contents is null meaning there is nothing in that slot. Check before hand if contents is null because when you try to use getType() you will get a NPE.

    edit: got sniped xD
     
  6. Offline

    Scullyking

    stormneo7 full as in no room at all? what if I want to add a torch, there are no empty slots but there are some torches already.
     
  7. Offline

    stormneo7

    That's different. .firstEmpty() only refers to the first slot available that has no items in it.
    Say that he had 1 torch and you want to give him 63 while the rest of the inventory is full.
    Using .firstEmpty() here will not benefit well.
     
Thread Status:
Not open for further replies.

Share This Page