Solved array index out of bounds

Discussion in 'Plugin Development' started by karolis11234, Jul 6, 2014.

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

    karolis11234

    i tried create a command that will explode the selected player:
    if (cmd.getName().equalsIgnoreCase("explo")) {
    Player target = sender.getServer().getPlayer(args[0]);
    if (target == null) {
    sender.sendMessage(args[0] + " is not currently online.");
    return true;
    }
    float explosionPower = 50F;
    target.getWorld().createExplosion(target.getLocation(), explosionPower);
    return true;
    }
    it gives me warnings when exporting and when i try using it , it doesnt work and it says in one place in the console when i use this command: ArrayIndexOutOfBounds: 0
    can anyone help me with this problem ?
     
  2. Offline

    endoml

    You need to check that args[0] exist before you can continue. Use args.length to make sure that arguments are being used.
     
  3. Offline

    mythbusterma

    You forgot to add a check to see if args actually has an element args[0], it could be an empty array.

    As an aside, I hope you realize just how large a "50" explosion is, it does a lot of damage and doesn't distribute properly either (you wind up with peculiar designs in your terrain).
     
  4. Offline

    karolis11234

    i changed it to this but it still doesnt work:
    if (cmd.getName().equalsIgnoreCase("explo")) {
    if(args.length == 0) {
    Player target = sender.getServer().getPlayer(args[0]);
    if (target == null) {
    sender.sendMessage(args[0] + " is not currently online.");
    return true;
    }
    float explosionPower = 50F;
    target.getWorld().createExplosion(target.getLocation(), explosionPower);
    return true;
    }
    }
     
  5. Offline

    endoml

    args.length == 0 checks that there are no arguments. Use args.length == 1
     
  6. Offline

    karolis11234

    changed to one but still got errors.
     
  7. Offline

    endoml

    What errors are you getting?
     
  8. Offline

    karolis11234

    exporting when i export it it says exported with warnings
     
  9. Offline

    HeadGam3z

    karolis11234
    You probably forgot to add an extra closing bracket when you added the argument check.
     
  10. Offline

    endoml

    I don't know if this is your problem, but you need to use an else after you check if the player is null. Right now, the plugin will create an explosion no matter if the player is null or not.
     
  11. Offline

    HeadGam3z

    endoml
    No, he doesn't need an else. If the target is null, it will just return, thus stopping the code. But if the target is not null, it will continue with the rest of the code (the explosion pow pow stuff)
     
  12. Offline

    karolis11234

Thread Status:
Not open for further replies.

Share This Page