How to check in command if args[X] is set? And question about exception.

Discussion in 'Spigot Plugin Development' started by Msql, Aug 29, 2017.

  1. How to check in command if args[X] is set?
    Yeah, it can be extremly easy question, but it is my first time I am creating command and unfortunetly I am having problems with it.
    I was trying:
    Code (Java):
    if (args[1] == null) {}
    But it is not working. This "if" is not running when there is no second argument.
    I know there is something like args.length, but is there any easier way to check it? Something that I will check if args[X] is set or not?

    Another question:
    Why, when there is no arguments in my command, like /command, my code is generating this exception:
    Code (Text):
    java.lang.ArrayIndexOutOfBoundsException: 0
    With the cause in this line:
    Code (Java):
    Thanks for any answer
  2. JustBru00


    I would think that the ArrayIndexOutOfBoundsException is caused by you trying to check args[x] when the length is not at least x long. You should check the length of the Array before trying to get data from it.

    Code (Text):
    if (args.length > 0) {
       //Length is greater than 0
    You can see an example from my plugin EpicRename on github here.
    • Agree Agree x 1
  3. Mas


    Use args.length to find the size of the array.
    • Agree Agree x 1
  4. Thanks!
    Can someone answer my second question? :x
  5. Mas


    That line wouldn't give an ArrayIndexOutOfBoundsException - that's caused when you try and access an element in an array which doesn't exist. That won't happen if you use args.length to check first.
  6. To expand on that: it's probably some outdated error (code changes occur frequently enough, you might've just changed a line without even realising).

    If the error seems vague (f.e. you're sure the error cannot be from a specific line, like your example), clear cache, rebuild & restart, it'll generally clear things up.
  7. Thanks!
    I have another question.
    Why, when I use command "/command test", this returns false:
    Code (Java):
    Boolean value = (args[0].toLowerCase() == "test");
    And this true:
    Code (Java):
    Boolean value2 = (args[0].equalsIgnoreCase("test"));

    Thanks for help! :)
  8. To compare two strings, you must be using String#equals(String), == arguments doesn't work
    • Useful Useful x 1
  9. FrostedSnowman

    Resource Staff

    use primitives for this case