CameronOfoluwa CameronOfoluwa - 4 months ago 11
Java Question

Bukkit Check Player's Inventory

I'm trying to see if a player has any of the following items in their inventory, and if they do, I want to remove the items and send them a message saying the item has been removed but I cannot figure out how to do it, this is what I have so far:

Material[] bannedItems = { Material.DIAMOND_HELMET, Material.DIAMOND_CHESTPLATE, Material.DIAMOND_LEGGINGS, Material.DIAMOND_BOOTS, Material.GOLD_HELMET, Material.GOLD_CHESTPLATE, Material.GOLD_LEGGINGS, Material.GOLD_BOOTS };

@EventHandler
public void onInventoryClick(InventoryClickEvent event) {
Player player = (Player) event.getWhoClicked();
if(player.getInventory().contains(bannedItems, 1)){
player.sendMessage(ChatColor.GRAY + "[" + ChatColor.RED + ChatColor.BOLD + "RPG" + ChatColor.GRAY + "] " + ChatColor.RED + "A has been removed from your possession.");
}
}


I get an error on the .contains(bannedItems, 1)) line.

Thanks for the help!

Answer

For every element in the array, you must check it, not just compare the array. Here is a proof of concept:

double[] check = {1.3, 4.2, 4.3}; //A sample double array

for(double d : check) { //Loop thru all elements
    if(4.2 == d) { //If current element is equal to 4.2
        System.out.println("EQUAL!"); //Print "EQUAL!"
    }
}

This loops over the check array one-by-one and compares each element to 4.2. It them reports when they are equal. You can then apply this to this situation:

@EventHandler
public void onInventoryClick(InventoryClickEvent event) {
    Material[] bannedItems = { Material.DIAMOND_HELMET, Material.DIAMOND_CHESTPLATE, Material.DIAMOND_LEGGINGS, Material.DIAMOND_BOOTS, Material.GOLD_HELMET, Material.GOLD_CHESTPLATE, Material.GOLD_LEGGINGS, Material.GOLD_BOOTS };
    Player player = (Player) event.getWhoClicked();

    for(Material m : bannedItems) { //Loop thru all elements
        if(player.getInventory().contains(m, 1)){ //Check if in inventory
            player.sendMessage(ChatColor.GRAY + "[" + ChatColor.RED + ChatColor.BOLD + "RPG" + ChatColor.GRAY + "] " + ChatColor.RED + "A has been removed from your possession.");
            //Remove stuff
        }
    }
}

Now, the event will loop through each element of the bannedItems and check if the user has it in there inventory.

for(Material m : bannedItems) 

Is an enhanced for loop that stores the current element in bannedItems in the m variable and then we compare using m, a single material.

I would also use a different event, such as when they pick up an item, and then check, so you can remove it right away.

Comments