首页 > 解决方案 > 在不应该执行的情况下执行其他操作

问题描述

我目前正在用 java 编写一个 minecraft 插件。但我面临一个问题,一个 else 语句被解雇了,而它不应该被解雇

我正在检查玩家是否在一个名为“安全区”的区域中,这将返回 true,我对此进行了调试。但是它会触发 else if 和 else 语句

我不确定为什么会发生这种情况,也不能完全确定。

这是我的方法

@EventHandler
public void entityDamageEvent(EntityDamageByEntityEvent event) {
    if (event.getEntity() instanceof Player) {
        Player attacker = (Player) event.getDamager();
        Player player = (Player) event.getEntity();
        Location location = player.getLocation();

        WorldGuardPlatform platform = com.sk89q.worldguard.WorldGuard.getInstance().getPlatform();
        RegionContainer container = platform.getRegionContainer();

        if (location.getWorld() != null) {
            RegionManager regionManager = container.get(BukkitAdapter.adapt(location.getWorld()));
            ApplicableRegionSet set = regionManager.getApplicableRegions(BukkitAdapter.asBlockVector(location));
            for (ProtectedRegion r : set) {
                if (r.getId().equals("safezone")) {

                    player.sendMessage("true");
                    attacker.sendMessage(ChatColor.RED + "Can't attack palyers here");
                } else {
                    attacker.sendMessage(ChatColor.RED + "You're now in combat, logging out will cost you!");
                    player.sendMessage(ChatColor.RED + "You're now in combat, logging out will cost you!");
                }
            }
        }
    }
}

我也会留下套装的内容

ProtectedRegion{id='arena', type='CUBOID'}
ProtectedRegion{id='safezone', type='CUBOID'}

标签: java

解决方案


对于所有r.getId.equals("safezone")为 false 的 ProtectedRegion 对象,将执行 else 块。例如:如果您总共有 10 个 ProtectedRegion 对象,并且有 6 个对象的id实例变量不是"safezone",那么您的 else 块将运行 6 次

这是假设您的 id 实例变量是 String 类型


推荐阅读