Hi guys, I get a ArrayIndexOutOfBounds error only when I run the command with a improper player name. I can't for the life of my understand what I did wrong. Code: public boolean onCommand(CommandSender sender, Command cmd, String CommandLabel, String args[]) { if (CommandLabel.equalsIgnoreCase("whereis")&& sender.hasPermission("EzzFind.whereis")) { Player[] online = Bukkit.getOnlinePlayers(); if(args.length == 1){ for (int i = 0; i <= online.length; i++){ Player player; player = this.getServer().getPlayer(args[0]); if (player == online[i]){ String name = player.getName(); String world = player.getLocation().getWorld().getName(); int X = (int)player.getLocation().getX(); int Y = (int)player.getLocation().getY(); int Z = (int)player.getLocation().getZ(); sender.sendMessage(name + ": " + world + " " + X + " " + Y + " " + Z); return true; } } }else if (args.length != 1){ sender.sendMessage("Only specify 1 player, no more no less"); return false; } } return false; }
Also, unless you do something else with it, I'd strongly suggest to drop the whole "online" array, as you don't need it. Just do Code: public boolean onCommand(CommandSender sender, Command cmd, String CommandLabel, String args[]) { if (CommandLabel.equalsIgnoreCase("whereis")&& sender.hasPermission("EzzFind.whereis")) { if(args.length == 1){ Player player; player = this.getServer().getPlayer(args[0]); if (player != null){ String name = player.getName(); String world = player.getLocation().getWorld().getName(); int X = (int)player.getLocation().getX(); int Y = (int)player.getLocation().getY(); int Z = (int)player.getLocation().getZ(); sender.sendMessage(name + ": " + world + " " + X + " " + Y + " " + Z); return true; } } else { sender.sendMessage("Only specify 1 player, no more no less"); return false; } } return false; } this.getServer().getPlayer(...) will only return players that are online anyway. So if a player with that name is online, you'll get it. If not, you'll get "null". EDIT: Fixed code snippet. Editor stole my linebreaks.
for (int i = 0; i <= online.length; i++){ should be written as: for (int i = 0; i < online.length; i++){ The length field gives you the number of elements in an array, but Java uses 0-based indexing, so array.length is one element past the end. As a stylistic recommendation, there's also no need to say else if (args.length != 1) - you can just use else here, since args.length is guaranteed not to be 1 at this point. But... why are you iterating through all the online players, in any case? Just do: PHP: Player player = this.getServer().getPlayer(args[0]);if (player != null) { // report the player's location} Oh, and you should use cmd.getName(), not CommandLabel when checking your command name. Otherwise one day you'll add an alias for your command and wonder why it doesn't work. EDIT: pah, beaten to it