Args onCommand check value

Status
This thread has been locked.

Clems02

Feedback score
0
Posts
15
Reactions
0
Resources
0
Hi,

I would like to use a command like this: / set mangouson efficiency 50.
It's for set efficienct enchant lvl 50 on an item.

But I want to check the value of args[0] and args[2] before check the enchant name of the args[1].
I want to check it to don't create exception and error in the console.

Code:
        if(cmd.getName().equalsIgnoreCase("set") && args.length == 3){
          
            //check args[0] and args[2]
          
            Player p = Bukkit.getPlayer(args[0]);
            int x = Integer.valueOf(args[2]);

          
            ItemStack item = p.getInventory().getItem(0);
            ItemMeta itemM = item.getItemMeta();
          
            if(args[1].equalsIgnoreCase("efficiency")) {
                              
                itemM.addEnchant(Enchantment.DIG_SPEED, x, true);
            }

Do you have a solution please ?
 
PebbleHost
High performance, consistent uptime and fast support. Minecraft hosting that just works.

_Torpedo_

Feedback score
0
Posts
41
Reactions
4
Resources
0
You should post the errors you're getting in the console. (Also please don't post it here, use something like hastebin.com)

If I were to guess, the errors are probably because the player isn't online (args[0]) and because enchantment level is not a number (args[2]).
To make sure player is online, check if "p" is null. (Since afterall, it should be a null pointer exception if I am not wrong)
Code:
Player p = Bukkit.getPlayer(args[0]);
if(p == null) {
  //Write an error message to player here and stop the function using return or something
}

To check whether enchantment level is a number (args[2]) try to parse it:
Code:
try {
  Integer.parseInt(args[2]);
} catch (NumberFormatException e) {
  //Write an error message to player here and stop the function
}

Try to research more about null and the Integer/wrapper classes in Java. These are not related to Spigot and rather development in general so they would help you further :)
 
Last edited:

Clems02

Feedback score
0
Posts
15
Reactions
0
Resources
0
It's work fine :D Ty !

Maybe do you have any tutorial from try/catch to manage exception ?
 
Status
This thread has been locked.
Top