Solved How do I check if a command argument is an Integer?

Discussion in 'Spigot Plugin Development' started by Fep310, Feb 20, 2020.

Thread Status:
Not open for further replies.
  1. The title explains it all.
    Here's the code that I'm working on:
    Code (Java):
    String uuid = target.getUniqueId().toString();
                        if (args[0].equalsIgnoreCase("set")) {
                            int pointsToSet = Integer.parseInt(args[2]);
                            PlayerStatsFile.get().set("Players." + uuid + ".Points", pointsToSet);
                            PlayerStatsFile.save();
                            sender.sendMessage(ChatColor.YELLOW+""+ChatColor.BOLD+">> " + ChatColor.YELLOW +
                                    "You've set " + args[2] + " points to " + target.getDisplayName());
    Full context on spoiler:
    I'm making a command to set or add player's points using an custom config file.

    Exemples on hoe the command should work:
    /points set Fep310 200
    /points add Fep310 30

    Here's the full class:
    Code (Java):
    package io.github.fep310.quickpvpplugin.Commands;

    import io.github.fep310.quickpvpplugin.Files.PlayerStatsFile;
    import org.bukkit.Bukkit;
    import org.bukkit.ChatColor;
    import org.bukkit.command.Command;
    import org.bukkit.command.CommandExecutor;
    import org.bukkit.command.CommandSender;
    import org.bukkit.entity.Player;

    public class ChangePointsCmd implements CommandExecutor {
        @Override
        public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {

            switch (args.length) {
                case 0:
                case 1:
                case 2:
                    sender.sendMessage(ChatColor.RED+""+ChatColor.BOLD+">> " + ChatColor.RED +
                            "Usage: /points <set/add> <player>");
                    break;
                case 3:
                    Player target = Bukkit.getPlayerExact(args[1]);
                    if (args[1] == null || args[2] == null) sender.sendMessage(ChatColor.RED+""+ChatColor.BOLD+">> " + ChatColor.RED +
                                "Usage: /points <set/add> <player>");

                    if (target != null) {
                        String uuid = target.getUniqueId().toString();
                        if (args[0].equalsIgnoreCase("set")) {
                            int pointsToSet = Integer.parseInt(args[2]);
                            PlayerStatsFile.get().set("Players." + uuid + ".Points", pointsToSet);
                            PlayerStatsFile.save();
                            sender.sendMessage(ChatColor.YELLOW+""+ChatColor.BOLD+">> " + ChatColor.YELLOW +
                                    "You've set " + args[2] + " points to " + target.getDisplayName());
                        } else if (args[0].equalsIgnoreCase("add")) {
                            int pointsToAdd = Integer.parseInt(args[2]);
                            int points = PlayerStatsFile.get().getInt("Players." + uuid + ".Points");
                            PlayerStatsFile.get().set("Players." + uuid + ".Points", points + pointsToAdd);
                            PlayerStatsFile.save();
                            sender.sendMessage(ChatColor.YELLOW+""+ChatColor.BOLD+">> " + ChatColor.YELLOW +
                                    "You've added " + args[2] + " points to " + target.getDisplayName());
                        } else {
                            sender.sendMessage(ChatColor.RED+""+ChatColor.BOLD+">> " + ChatColor.RED +
                                    "Usage: /points <set/add> <player>");
                        }
                    } else sender.sendMessage(ChatColor.RED+""+ChatColor.BOLD+">> " + ChatColor.RED +
                            "This player doesn't exists or isn't online");
                    break;
                default:
                    sender.sendMessage(ChatColor.RED+""+ChatColor.BOLD+">> " + ChatColor.RED +
                            "This command doesn't support more than 2 arguments");
            }
            return true;
        }
    }
     

    Thanks for your time <3
     
    • Like Like x 1
  2. Basically what @Bobcat00 said but with a little utility method:

    Code (Java):
    public static boolean isInt(String s) {
            try {
                Integer.parseInt(s);
            } catch (NumberFormatException nfe) {
                return false;
            }
            return true;
        }
    then you could do it like this for example:
    Code (Java):
    if (args.length == 1 && isInt(args[0])) {
    ...
     
    • Winner Winner x 1
    • Useful Useful x 1
  3. Alternatively, you could use NumberUtils#isParsable from Apache Commons to simply determine if the String is an integer without a try-catch block.
     
    • Agree Agree x 2
    • Creative Creative x 2
  4. Thank you all for your attention, I got it working properly! c:
    And also, I'm using the "isInt" method but I'll try to study the "isParsable" method later.

    The working final code:
    Code (Java):
    package io.github.fep310.quickpvpplugin.Commands;

    import io.github.fep310.quickpvpplugin.Files.PlayerStatsFile;
    import org.bukkit.Bukkit;
    import org.bukkit.ChatColor;
    import org.bukkit.command.Command;
    import org.bukkit.command.CommandExecutor;
    import org.bukkit.command.CommandSender;
    import org.bukkit.entity.Player;

    public class ChangePointsCmd implements CommandExecutor {

        public static boolean isInt(String s, CommandSender sender) {
            try {
                Integer.parseInt(s);
            } catch (NumberFormatException nfe) {
                sender.sendMessage(ChatColor.RED+""+ChatColor.BOLD+">> " + ChatColor.RED +
                        "It is necessary to use a number on the third argument.");
                return false;
            }
            return true;
        }

        @Override
        public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {

            switch (args.length) {
                case 0:
                case 1:
                case 2:
                    sender.sendMessage(ChatColor.RED+""+ChatColor.BOLD+">> " + ChatColor.RED +
                            "Usage: /points <set/add> <player> <value>");
                    break;
                case 3:
                    Player target = Bukkit.getPlayerExact(args[1]);
                    if (args[1] == null || args[2] == null) sender.sendMessage(ChatColor.RED+""+ChatColor.BOLD+">> " + ChatColor.RED +
                                "Usage: /points <set/add> <player> <value>");

                    if (target != null) {
                        if (isInt(args[2], sender)) {
                            String uuid = target.getUniqueId().toString();
                            if (args[0].equalsIgnoreCase("set")) {
                                int pointsToSet = Integer.parseInt(args[2]);
                                PlayerStatsFile.get().set("Players." + uuid + ".Points", pointsToSet);
                                PlayerStatsFile.save();
                                sender.sendMessage(ChatColor.YELLOW+""+ChatColor.BOLD+">> " + ChatColor.YELLOW +
                                        "You've set " + args[2] + " points to " + target.getDisplayName());
                            } else if (args[0].equalsIgnoreCase("add")) {
                                int pointsToAdd = Integer.parseInt(args[2]);
                                int points = PlayerStatsFile.get().getInt("Players." + uuid + ".Points");
                                PlayerStatsFile.get().set("Players." + uuid + ".Points", points + pointsToAdd);
                                PlayerStatsFile.save();
                                sender.sendMessage(ChatColor.YELLOW+""+ChatColor.BOLD+">> " + ChatColor.YELLOW +
                                        "You've added " + args[2] + " points to " + target.getDisplayName());
                            } else sender.sendMessage(ChatColor.RED+""+ChatColor.BOLD+">> " + ChatColor.RED +
                                    "Usage: /points <set/add> <player> <value>");
                        }
                    } else sender.sendMessage(ChatColor.RED+""+ChatColor.BOLD+">> " + ChatColor.RED +
                            "This player doesn't exists or isn't online");
                    break;
                default:
                    sender.sendMessage(ChatColor.RED+""+ChatColor.BOLD+">> " + ChatColor.RED +
                            "This command doesn't support more than 2 arguments");
            }
            return true;
        }
    }
     
    <3
     
    • Friendly Friendly x 4
  5. isParsable pretty much does what your isInt method does, except for sending a message of course. It's just a convenience method for a common situation.
     
  6. FrostedSnowman

    Resource Staff

    For this case, it's better to catch any exception that could be thrown from parsing it. :) Here's why:
    • Allows for exception handling, essentially telling the end user that the argument was unable to be parsed
    • NumberUtils::isParsable will allow any decimal value, OP does not seem to be dealing with decimals
    • Often times, when using a library to check for such things, it's typically using Integer#parseInt, or any of its variants, under the hood. This will avoid a double invocation of Integer#parseInt, especially when wanting to work with the result
    @OP, Alternatively, if you wanted there to be a default value if the number is un-parsable, you could use NumberUtils::toInt or any of the variants (toLong, toDouble, etc).
     
    • Informative Informative x 1
    • Useful Useful x 1
Thread Status:
Not open for further replies.