错误getPlayer(args [0]);

时间:2015-07-30 13:35:05

标签: java minecraft bukkit

我制作了这段代码,如果你在MC中键入:/ gmspec我应该将你的游戏模式设置为Spectator模式。但它唯一说的是:'尝试执行此命令时发生内部错误。'。在控制台中它说:arrayindexoutofboundsException:0 ...请帮助,我不知道这是什么问题......

    if (commandLabel.equalsIgnoreCase("gmspec")) {


        Player p = (Player) sender;
        Player target = Bukkit.getServer().getPlayer(args[0]);


        if (args.length == 0) {
            p.setGameMode(GameMode.SPECTATOR);
            p.sendMessage(ChatColor.GREEN + "Your own gamemode has been changed!");
            return true;
        }

        if (target == null) {
            p.sendMessage(ChatColor.RED + "The player " + target.getName() + " is not online!");
            return true;

        }
        target.setGameMode(GameMode.SPECTATOR);
        target.sendMessage(ChatColor.GREEN + "Your gamemode is set to Spectator mode. You are not a banaan that just tries every command without any permission...");

        if (sender.hasPermission("gamemode.spectator")) {

            p.sendMessage(ChatColor.RED + "You banaan. Y u still try? U no permission has u dumb shit");
        }
        if (sender instanceof ConsoleCommandSender) {


        }


    }
    return true;
}

1 个答案:

答案 0 :(得分:1)

您的问题是,在尝试获取参数后,您需要检查参数的长度。在尝试获取参数之前,您必须确保有一个或多个参数,否则您将获得ArrayIndexOutOfBoundsException

此外,您还要在将命令发件人转换为char之前检查命令发件人是否为Player。如果你不这样做,你将无法从Player以外的任何地方运行命令。

要解决此问题,您可以使用Player替换每个p.sendMessage(),如果sender.sendMessage()

,则仅将sender转换为Player

所以,你的代码可能看起来像这样

sender instanceof Player