java - BUKKIT 插件 API : How can I check if a player's inventory contains an item included in an array?

标签 java arrays bukkit inventory

我正在用 Java 制作一个名为 BanItemsBukkit 插件。我在创建它时遇到了多个问题,而且我在任何地方都找不到答案。所以我问了这个问题。 在代码中,我有一个数组 ItemsBanned[ ],并且仅包含字符串。 我想检查并查看是否有任何玩家的库存中有该数组中的元素。

public void onPlayerJoin(PlayerJoinEvent event) {
    Player player = event.getPlayer();
    Inventory inv = player.getInventory();


    if (inv.contains(itemsBanned[x])) {

     }

出于某种奇怪的原因,当我将代码复制并粘贴到此处时,无论我对 4 个空格之类的东西做什么,它都会完全卡住。所以,这就是我能展示的全部内容。

它不会让我查看玩家的库存是否包含数组 itemsBanned 中的项目。 我怎样才能做到这一点? 请回答。

最佳答案

您可以使用一个简单的 for 循环。我将从您的问题假设 ItemsBanned 是项目名称。

for(int i = 0; i < itemsBanned.length(); i++){
    Material m = Material.getMaterial(itemsBanned[i]); //convert the strings to Materials
    if(inv.contains(m)){
        //do something here
    }
}

该代码的唯一问题是您无法删除这些元素,只有当玩家拥有一个或多个元素时您才会收到警报。如果您想删除禁止的项目,您可以这样做:

for(int i = 0; i < itemsBanned.length(); i++){
    Material m = Material.getMaterial(itemsBanned[i]); //convert the strings to Materials

    for(int n = 0; n < inv.getSize(); n++){ //loop threw all items in the inventory
        ItemStack itm = inv.getItem(n); //get the items
        if(itm != null){ //make sure the item is not null, or you'll get a NullPointerException
            if(itm.getType().equals(m)){ //if the item equals a contraband item
                inv.remove(m); //remove the item
            }
        }
    }
}

关于java - BUKKIT 插件 API : How can I check if a player's inventory contains an item included in an array?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22264930/

相关文章:

java - Selenium Webdriver 和 Java。元素在点 (x, y) 处不可单击。其他元素将收到点击

javascript - 在javascript中设置对象数组的顺序

javascript - 从服务器异步请求后将数据推送到数组的特定索引

java - GraalVM - 在类路径上找不到语言和多语言实现

java - Maven 资源过滤不起作用 - 因为 spring boot 依赖

java - JTextArea append() 方法写入两次?

python - 在 Python 中解析 JSON 数组

java - Bukkit 插件无法正常工作

java - 给玩家体验

java - @FXML 自定义组件注入(inject)不会实例化 Controller 中的变量并导致 NullPointerException