Solved Check for an array that may be non-existent.

Discussion in 'Spigot Plugin Development' started by Wilsoon, Mar 1, 2020.

Thread Status:
Not open for further replies.
  1. So, I have my onCommand as usual, and it has two arguments with the index at args[0] and args[1], I've made it so that args[0] is a required array (Player), however I want to make it so that args[1] (Long) is optional. However this is how i'm trying to do it:
    Code (Java):
    if(args[1] != null) {
                    timeinticks = Long.parseLong(args[1]);
                    } else {
                        timeinticks = 12000L;
                        sender.sendMessage(ChatColor.GOLD + "Time in ticks not specified! Default time of 10 minutes chosen.");
                    }
    However, I'm instead receiving the ArrayIndexOutOfBoundsException if I don't specify. How do I make it optional?
     
  2. SteelPhoenix

    Moderator

    You can't access an element in an array if it doesn't exist, so ensure it exists by checking if the index you're trying to access is within the array's bounds first (0 <= x < array size)
     
  3. Check if the length of the array is greater than 1.
     
  4. Never checked array bounds before, how do I find x and array size?
     
  5. args.length is what you are looking for:

    Code (Java):
    if (args.length == 0) {
             
                //no arguments
             
            } if (args.length == 1) {

                //1 argument

            } else {

                //2 or more arguments

            }
     
    • Like Like x 1
  6. Please note that this is not a Java school, next time please look things up before asking.
     
    • Agree Agree x 1
  7. Ok. Thanks.
     
Thread Status:
Not open for further replies.