If args[0] is an INTEGER

Discussion in 'Plugin Development' started by iKeirNez, Feb 15, 2012.

Thread Status:
Not open for further replies.
  1. I am using the following code in my time command:

    http://pastebin.com/PrJ73T2P

    How can I check if args[0] is an int so players can also do /time 0 .

    Help would be greatly appreciated
    Keir
     
  2. Offline

    theguynextdoor

    I use these methods:
    Code:java
    1. public static int getInt(String string) {
    2. if (isInt(string)) {
    3. return Integer.parseInt(string);
    4. }
    5. else {
    6. return 0;
    7. }
    8. }
    9.  
    10. public static boolean isInt(String string) {
    11. try {
    12. Integer.parseInt(string);
    13. } catch (NumberFormatException nFE) {
    14. return false;
    15. }
    16. return true;
    17. }
     
  3. I'll try that out, thanks!
     
  4. Offline

    Njol

    This function has 4 issues:
    1. If the input isn't an integer, a NumberFormatException is thrown.
    2. Integer.equals(string) does either not work or is a waste of CPU cycles.
    these two are minor, but still:
    3. If you don't need an instance of Integer don't use one. Use an int wherever possible.
    4. "if (boolean) return true; else return false;" is equal to "return boolean;".
     

  5. This looks like the perfect one, thanks.
     
  6. Offline

    Njol

    Except that it parses the number 2 times where once would be enough:
    Code:java
    1. public static int getInt(String string) {
    2. try {
    3. return Integer.parseInt(string);
    4. } catch (NumberFormatException nFE) {
    5. return 0;
    6. }
    7.  
    8. }
    9.  
    10. public static boolean isInt(String string) {
    11. try {
    12. Integer.parseInt(string);
    13. } catch (NumberFormatException nFE) {
    14. return false;
    15. }
    16. return true;
    17. }
     
  7. Offline

    llamasaylol

    I haven't tried this, but you might be able to use this.
    Code:java
    1. if (args[0].matches("[-+]?\\d+(\\.\\d+)?") == true) {
    2. //Do stuff
    3. return true;
    4. } else {
    5. //Send them a message or something
    6. }


    Source: at about 3:35
     
  8. Offline

    Taco

    Here's how I would do it:

    try{
    Integer.parseInt(args[0]);
    //Do stuff here. Will only execute if the above code doesn't throw an exception.
    } catch(Exception e) {
    //Do other stuff. In this case, it's not an int.
    }
     
    nelson2tm and TopGear93 like this.
  9. Thanks for all your replies! When I get back to my coding pc I will try these out. Thanks
     
  10. Offline

    Zimp

     
Thread Status:
Not open for further replies.

Share This Page