java.lang.ArrayIndexOutOfBoundsException Problems

Discussion in 'Plugin Development' started by tschagg, Jun 6, 2013.

Thread Status:
Not open for further replies.
  1. Offline

    tschagg

    hey guys, im workin on a little banlist mysql plugin, which filters out the ban command and get the arguments of it.
    now when i type /ban player test, all is fine.
    but when i only type /ban test, or just /ban, is got java.lang.ArrayIndexOutOfBoundsException errors.
    it seems like args[1] is never null, strange...

    maybe someone can help me with that?

    code:

    Code:
        public void onPlayerCommandPreprocess(final PlayerCommandPreprocessEvent event) {
            String args[] = event.getMessage().split(" ");
            Player player2 = event.getPlayer();
            mod = player2.getName();
            String player = args[1];
            String[] split = event.getMessage().split("\\s+");
            String command = split[0].substring(1);
            if (command.equalsIgnoreCase("ban")) {
                if (args[1] == null) {
                      event.getPlayer().sendMessage("Keine Message!");
                    event.setCancelled(true);
                }
                if (args[2] != null) {
                    for (int i = 2; i < args.length; i++) {
                        reason += args[i] + " ";
                    }
                } else {
                    reason = "Banned";
                }
                player = this.setBanned(player, reason, mod);
            }
        }
    thank you!
     
  2. Offline

    Rocoty

    You've got to remember that when doing args[1] you're asuming that the length of args is 2 or greater.
    Java will throw an ArrayIndexOutOfBoundsException when you try to access an index of an array, which isn't technically there.

    So do not check if args[1] is null, which, in this case, it probably never will be. Instead, check if the length of args is 2 or greater:
    Code:
    args.length >= 2
    Use this method for checking if an index exists
     
    tschagg likes this.
  3. Offline

    CubieX

    If you type /ban and no argument, this means that args[0], args[1] and so on will be "non-existant".
    This is not (always) the same as "null".
    In this case, it's not.

    So what you have to do is: Check if "args.length == 1" or whatever argument count you expect for a specific command,
    before accessing this args[x] element.
    No need to check for "null" here.

    EDIT: ninja'd ;)
     
    tschagg likes this.
  4. Offline

    tschagg

    ok thank you so much! it worked :D
     
Thread Status:
Not open for further replies.

Share This Page