Search code examples
javaminecraftbukkit

How to ignore args[1] in the else/if


I trying to do a Fake plugin to my server, but I don't know how to solve this error in game: "An internal error occurred while attempting to perform this command" It's because I trying to use args[], I can use args[0] with no problems, but, if I put args[1], this error occurs (If I don't write anything in args[1], but if I remove args[1] and don't write anything in args[0] it works) An example of my code:

public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
    
    Player p = (Player)sender;
    String error = "§4§l404!";
    String noPerm = error + " §cYou don't have permission!";
    
    if(p.hasPermission("perm.fake")) {
        if(cmd.getLabel().equalsIgnoreCase("fake")) {
            if(args[0].equalsIgnoreCase("reset")) {
                p.setCustomName(p.getName());
                p.setCustomNameVisible(false);
                p.setDisplayName(p.getName());
                p.setPlayerListName(p.getName());
            } else if(args[0].length() == 0) {
                p.sendMessage(error + "§cYou need to specify a fake!");
            } else if(args[1].length() == 0) { **//Here is the part I need help**
                p.setCustomName(args[0].replace('&', '§'));
                p.setCustomNameVisible(true);
                p.setDisplayName(p.getCustomName()); **//These part don't works if I dont write anything in args[1]**
                p.setPlayerListName(p.getCustomName());
            } else if(args[1].equalsIgnoreCase("r")) {
                **//Here have a long code, it works if I write the char "r" in command**
            }
        }
    } else {
        p.sendMessage(noPerm);
    }
    return false;
}

I only want if I don't write anything in the args[1] the command sets the fake without anything special that I put in "r"


Solution

  • If you do not write at least two arguments then trying to access args[1] will result in ArrayOutOfBoundsException as the array does only contain one String (args[0]). To prevent that you have two workarounds:

    First solution: Change the if condition Instead of checking if args[1] equals 0 which will trigger an exception check if the array length is smaller than 2.

    } else if(args.length < 2) { **//Here is the part I need help**
    

    Second solution: Check the number of arguments. If you want to force the user to input at least two arguments to the command you can just add at the beginning of your function:

    if(args.length < 2) {
        sender.sendMessage(ChatColor.RED + "You must use two arguments!");
        return false;
    }
    

    Let me know if it helps!