Solved How can I check, if args[1] is an int variable?

Discussion in 'Plugin Development' started by RedstonecraftHD, Jun 14, 2019.

Thread Status:
Not open for further replies.
  1. How can i check if the user input of args[1] is an int and when it isnt?


    I hope somebody can help me
     
  2. Offline

    Tango_

    You can use this from the Apache Commons class that I prefer to use because its simple.

    Code:
                if(StringUtils.isNumeric(args[1])) {
                  
                    // Is number
                  
                } else {
                  
                    // Not number
                  
                }
     
    RedstonecraftHD likes this.
  3. Thanks for you fast and useful answer! :D
     
  4. Offline

    KarimAKL

    @RedstonecraftHD Another way that doesn't require a library is this:
    Code:Java
    1. int number = 0;
    2. try {
    3. number = Integer.parseInt(args[1]);
    4. } catch (NumberFormatException e) {
    5. sender.sendMessage("\""+args[1]+"\" is not a number!");
    6. return true;
    7. }
    8. sender.sendMessage("\""+number+"\" is a number!");
     
    Kars likes this.
  5. What @KarimAKL would be best case but I'd make a helper method so you don't fill onCommand with try catches.

    Code:java
    1. private int getInt(String str, int defaultVal) {
    2. try {
    3. return Integer.parseInt(str);
    4. } catch(NumberFormatException e) {
    5. return defaultVal;
    6. }
    7. }
    8.  
    9. // Then in onCommand
    10. int x = getInt(args[1], -1);
    11. if (x == -1) {
    12. player.sendMessage("Dun goofed");
    13. return true;
    14. }
    15.  
    16. player.sendMessage("X: " + x);
     
    Kars likes this.
Thread Status:
Not open for further replies.

Share This Page