What's the best way to check if a String represents an integer in Java?

后端 未结 30 1434
野趣味
野趣味 2020-11-22 05:45

I normally use the following idiom to check if a String can be converted to an integer.

public boolean isInteger( String input ) {
    try {
        Integer.         


        
相关标签:
30条回答
  • 2020-11-22 06:11

    If you are using the Android API you can use:

    TextUtils.isDigitsOnly(str);
    
    0 讨论(0)
  • 2020-11-22 06:12

    How about:

    return Pattern.matches("-?\\d+", input);
    
    0 讨论(0)
  • 2020-11-22 06:12

    You may try apache utils

    NumberUtils.isCreatable(myText)
    

    See the javadoc here

    0 讨论(0)
  • 2020-11-22 06:13

    You just check NumberFormatException:-

     String value="123";
     try  
     {  
        int s=Integer.parseInt(any_int_val);
        // do something when integer values comes 
     }  
     catch(NumberFormatException nfe)  
     {  
              // do something when string values comes 
     }  
    
    0 讨论(0)
  • 2020-11-22 06:17

    You probably need to take the use case in account too:

    If most of the time you expect numbers to be valid, then catching the exception is only causing a performance overhead when attempting to convert invalid numbers. Whereas calling some isInteger() method and then convert using Integer.parseInt() will always cause a performance overhead for valid numbers - the strings are parsed twice, once by the check and once by the conversion.

    0 讨论(0)
  • 2020-11-22 06:18

    This is shorter, but shorter isn't necessarily better (and it won't catch integer values which are out of range, as pointed out in danatel's comment):

    input.matches("^-?\\d+$");
    

    Personally, since the implementation is squirrelled away in a helper method and correctness trumps length, I would just go with something like what you have (minus catching the base Exception class rather than NumberFormatException).

    0 讨论(0)
提交回复
热议问题