错误 getPlayer(args[0]);

Error getPlayer(args[0]);

我编写了这段代码,如果您在 MC 中键入:/gmspec,我应该将您的游戏模式设置为观众模式。但它唯一说的是:'An Internal error occurred while attempting to perform this command.'。在控制台中显示: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;
}

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

此外,在将它们转换为 Player 之前,您需要检查命令发送者是否确实是 Player。如果不这样做,除了 Player.

之外,您将无法 运行 命令

要解决此问题,您可以将每个 p.sendMessage() 替换为 sender.sendMessage(),并且仅在 sender instanceof Player[=21= 时将 sender 转换为 Player ]

因此,您的代码可能如下所示

if(commandLabel.equalsIgnoreCase("gmspec")){
    if(args.length == 0 && sender instanceof Player){//check if the sender is a Player
        Player p = (Player) sender; 

        p.setGameMode(GameMode.SPECTATOR);
        p.sendMessage(ChatColor.GREEN + "Your own gamemode has been changed!");

        return true;
    }
    else{
        Player target = Bukkit.getServer().getPlayer(args[0]);

        //the rest of the code
    }
}