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

后端 未结 30 1437
野趣味
野趣味 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:22

    I believe there's zero risk running into an exception, because as you can see below you always safely parse int to String and not the other way around.

    So:

    1. You check if every slot of character in your string matches at least one of the characters {"0","1","2","3","4","5","6","7","8","9"}.

      if(aString.substring(j, j+1).equals(String.valueOf(i)))
      
    2. You sum all the times that you encountered in the slots the above characters.

      digits++;
      
    3. And finally you check if the times that you encountered integers as characters equals with the length of the given string.

      if(digits == aString.length())
      

    And in practice we have:

        String aString = "1234224245";
        int digits = 0;//count how many digits you encountered
        for(int j=0;j<aString.length();j++){
            for(int i=0;i<=9;i++){
                if(aString.substring(j, j+1).equals(String.valueOf(i)))
                        digits++;
            }
        }
        if(digits == aString.length()){
            System.out.println("It's an integer!!");
            }
        else{
            System.out.println("It's not an integer!!");
        }
        
        String anotherString = "1234f22a4245";
        int anotherDigits = 0;//count how many digits you encountered
        for(int j=0;j<anotherString.length();j++){
            for(int i=0;i<=9;i++){
                if(anotherString.substring(j, j+1).equals(String.valueOf(i)))
                        anotherDigits++;
            }
        }
        if(anotherDigits == anotherString.length()){
            System.out.println("It's an integer!!");
            }
        else{
            System.out.println("It's not an integer!!");
        }
    

    And the results are:

    It's an integer!!

    It's not an integer!!

    Similarly, you can validate if a String is a float or a double but in those cases you have to encounter only one . (dot) in the String and of course check if digits == (aString.length()-1)

    Again, there's zero risk running into a parsing exception here, but if you plan on parsing a string that it is known that contains a number (let's say int data type) you must first check if it fits in the data type. Otherwise you must cast it.

    I hope I helped

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

    When explanations are more important than performance

    I noticed many discussions centering how efficient certain solutions are, but none on why an string is not an integer. Also, everyone seemed to assume that the number "2.00" is not equal to "2". Mathematically and humanly speaking, they are equal (even though computer science says that they are not, and for good reason). This is why the "Integer.parseInt" solutions above are weak (depending on your requirements).

    At any rate, to make software smarter and more human-friendly, we need to create software that thinks like we do and explains why something failed. In this case:

    public static boolean isIntegerFromDecimalString(String possibleInteger) {
    possibleInteger = possibleInteger.trim();
    try {
        // Integer parsing works great for "regular" integers like 42 or 13.
        int num = Integer.parseInt(possibleInteger);
        System.out.println("The possibleInteger="+possibleInteger+" is a pure integer.");
        return true;
    } catch (NumberFormatException e) {
        if (possibleInteger.equals(".")) {
            System.out.println("The possibleInteger=" + possibleInteger + " is NOT an integer because it is only a decimal point.");
            return false;
        } else if (possibleInteger.startsWith(".") && possibleInteger.matches("\\.[0-9]*")) {
            if (possibleInteger.matches("\\.[0]*")) {
                System.out.println("The possibleInteger=" + possibleInteger + " is an integer because it starts with a decimal point and afterwards is all zeros.");
                return true;
            } else {
                System.out.println("The possibleInteger=" + possibleInteger + " is NOT an integer because it starts with a decimal point and afterwards is not all zeros.");
                return false;
            }
        } else if (possibleInteger.endsWith(".")  && possibleInteger.matches("[0-9]*\\.")) {
            System.out.println("The possibleInteger="+possibleInteger+" is an impure integer (ends with decimal point).");
            return true;
        } else if (possibleInteger.contains(".")) {
            String[] partsOfPossibleInteger = possibleInteger.split("\\.");
            if (partsOfPossibleInteger.length == 2) {
                //System.out.println("The possibleInteger=" + possibleInteger + " is split into '" + partsOfPossibleInteger[0] + "' and '" + partsOfPossibleInteger[1] + "'.");
                if (partsOfPossibleInteger[0].matches("[0-9]*")) {
                    if (partsOfPossibleInteger[1].matches("[0]*")) {
                        System.out.println("The possibleInteger="+possibleInteger+" is an impure integer (ends with all zeros after the decimal point).");
                        return true;
                    } else if (partsOfPossibleInteger[1].matches("[0-9]*")) {
                        System.out.println("The possibleInteger=" + possibleInteger + " is NOT an integer because it the numbers after the decimal point (" + 
                                    partsOfPossibleInteger[1] + ") are not all zeros.");
                        return false;
                    } else {
                        System.out.println("The possibleInteger=" + possibleInteger + " is NOT an integer because it the 'numbers' after the decimal point (" + 
                                partsOfPossibleInteger[1] + ") are not all numeric digits.");
                        return false;
                    }
                } else {
                    System.out.println("The possibleInteger=" + possibleInteger + " is NOT an integer because it the 'number' before the decimal point (" + 
                            partsOfPossibleInteger[0] + ") is not a number.");
                    return false;
                }
            } else {
                System.out.println("The possibleInteger="+possibleInteger+" is NOT an integer because it has a strange number of decimal-period separated parts (" +
                        partsOfPossibleInteger.length + ").");
                return false;
            }
        } // else
        System.out.println("The possibleInteger='"+possibleInteger+"' is NOT an integer, even though it has no decimal point.");
        return false;
    }
    }
    

    Test code:

    String[] testData = {"0", "0.", "0.0", ".000", "2", "2.", "2.0", "2.0000", "3.14159", ".0001", ".", "$4.0", "3E24", "6.0221409e+23"};
    int i = 0;
    for (String possibleInteger : testData ) {
        System.out.println("");
        System.out.println(i + ". possibleInteger='" + possibleInteger +"' isIntegerFromDecimalString=" + isIntegerFromDecimalString(possibleInteger));
        i++;
    }
    
    0 讨论(0)
  • 2020-11-22 06:25

    If your String array contains pure Integers and Strings, code below should work. You only have to look at first character. e.g. ["4","44","abc","77","bond"]

    if (Character.isDigit(string.charAt(0))) {
        //Do something with int
    }
    
    0 讨论(0)
  • 2020-11-22 06:25

    To check for all int chars, you can simply use a double negative.

    if (!searchString.matches("[^0-9]+$")) ...

    [^0-9]+$ checks to see if there are any characters that are not integer, so the test fails if it's true. Just NOT that and you get true on success.

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

    Just one comment about regexp. Every example provided here is wrong!. If you want to use regexp don't forget that compiling the pattern take a lot of time. This:

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

    and also this:

    Pattern.matches("-?\\d+", input);
    

    causes compile of pattern in every method call. To used it correctly follow:

    import java.util.regex.Pattern;
    
    /**
     * @author Rastislav Komara
     */
    public class NaturalNumberChecker {
        public static final Pattern PATTERN = Pattern.compile("^\\d+$");
    
        boolean isNaturalNumber(CharSequence input) {
            return input != null && PATTERN.matcher(input).matches();
        }
    }
    
    0 讨论(0)
  • 2020-11-22 06:27

    Another option:

    private boolean isNumber(String s) {
        boolean isNumber = true;
        for (char c : s.toCharArray()) {
            isNumber = isNumber && Character.isDigit(c);
        }
        return isNumber;
    }
    
    0 讨论(0)
提交回复
热议问题