Solved Help with arguments and integer errors

Discussion in 'Plugin Development' started by JakeCPU, May 24, 2017.

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

    JakeCPU

    Hello, first of all I would like to point out I am a complete Novice at coding with Spigot/Bukkit and Java in general, so recently I have been creating this sort of extra essentials plugin and I have come across a command I would want to add called /addxp <XP>, the command is simple you would just type /addxp and then the amount of EXP you would want added to you. So I tried this piece of code but it does not seem to be working. Can anyone help?

    Code:
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
            Player player = (Player) sender;
           
            if(command.getName().equalsIgnoreCase("test")) {
                if(args.length == 1) {
                    player.giveExp(args);
                }else{
                    player.sendMessage(ChatColor.RED + "Invalid Usage: /addxp <xp>");
                }
            }
           
            return false;
            }
    
    The error is: The method giveExp(int) in the type Player is not applicable for the arguments (String[]) on line player.giveExp(args);

    (This is probably a really dummy question but like I said im new to plugin developing. :p)
     
    Last edited: May 24, 2017
  2. Offline

    Zombie_Striker

    @JakeCPU
    You are providing all the args for the command instead of just the XP (Also note that this is the Raw Xp, not the levels). Here is what you need to do:
    1. Get the first arg using args[0]
    2. Turn the first arg into an Integer using Integer.parseInt(...);
    3. [Optional] Add a try/catch case around the integer parsing. The player may not provide a number, so doing this will make sure you can tell them to provide a real number and will make sure there will not be errors in the console.
    4. Provide that number for the giveExp method.
     
  3. Offline

    JakeCPU

    This is probably a stupid question but how would I be able to get the first arg where I would be able to use Integer.parseInt(...)?
     
  4. Offline

    Zombie_Striker

    @JakeCPU
    1. To get the first arg, use args[0]
    2. Ideally, you would create an int variable that is empty/ set to 0. Then, set up a try/catch statement. Inside the try part, set that int equal to the Integer.parseInt(args[0]). This will attempt to set the number equal to the one provided in the command (if the player did provide a number). Then, in the catch statement, you would send a player a message saying they need to provide the Xp as a number, as this would case would only be triggered if the command was sent incorrectly, and then returning so that does not continue. Then, after you set all that up, you would set the Xp to be equal to the int variable.
     
Thread Status:
Not open for further replies.

Share This Page