我正在用 Java 制作一个名为 BanItems 的 Bukkit 插件。我在创建它时遇到了多个问题,而且我在任何地方都找不到答案。所以我问了这个问题。 在代码中,我有一个数组 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/