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

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

    This is a modification of Jonas' code that checks if the string is within range to be cast into an integer.

    public static boolean isInteger(String str) {
        if (str == null) {
            return false;
        }
        int length = str.length();
        int i = 0;
    
        // set the length and value for highest positive int or lowest negative int
        int maxlength = 10;
        String maxnum = String.valueOf(Integer.MAX_VALUE);
        if (str.charAt(0) == '-') { 
            maxlength = 11;
            i = 1;
            maxnum = String.valueOf(Integer.MIN_VALUE);
        }  
    
        // verify digit length does not exceed int range
        if (length > maxlength) { 
            return false; 
        }
    
        // verify that all characters are numbers
        if (maxlength == 11 && length == 1) {
            return false;
        }
        for (int num = i; num < length; num++) {
            char c = str.charAt(num);
            if (c < '0' || c > '9') {
                return false;
            }
        }
    
        // verify that number value is within int range
        if (length == maxlength) {
            for (; i < length; i++) {
                if (str.charAt(i) < maxnum.charAt(i)) {
                    return true;
                }
                else if (str.charAt(i) > maxnum.charAt(i)) {
                    return false;
                }
            }
        }
        return true;
    }
    

提交回复
热议问题