[JAVA] Check if a string can be converted to an int without using Integer # parseInt

If you want to check whether the input character string is converted to int type, you may see the source code that judges as follows.

try {
    Integer.parseInt(str);
    return true;
} catch (NumberFormatException e) {
    return false;
}

__ I personally felt uncomfortable with this method, such as converting it to false if it didn't work, and then squeezing the exceptions, so I was somehow shunned. __ To put it plainly, I have a physiological disgust.

That's why I made a method __ to check if a given string can be converted to an int without using __ʻInteger # parseInt` (´ ・ ω ・ `)

final public class IntegerUtils {
    
    public static void main(String[] args) {
        System.out.println(IntegerUtils.isInteger("123")); //=> true
        System.out.println(IntegerUtils.isInteger("-23")); //=> true
        System.out.println(IntegerUtils.isInteger("12A")); //=> false
        System.out.println(IntegerUtils.isInteger("ABC")); //=> false
        
        //Even the boundary value can be judged accurately.
        System.out.println(IntegerUtils.isInteger("2147483647")); //=> true
        System.out.println(IntegerUtils.isInteger("2147483648")); //=> false
        System.out.println(IntegerUtils.isInteger("-2147483648")); //=> true
        System.out.println(IntegerUtils.isInteger("-2147483649")); //=> false
        
        // ==== 2017-05-16 Added test cases.===
        System.out.println(IntegerUtils.isInteger("0")); //=> true
        System.out.println(IntegerUtils.isInteger("473")); //=> true
        System.out.println(IntegerUtils.isInteger("+42")); //=> true
        System.out.println(IntegerUtils.isInteger("-0")); //=> true

        System.out.println(IntegerUtils.isInteger("-")); //=> false
        System.out.println(IntegerUtils.isInteger("+5")); //=> true
        System.out.println(IntegerUtils.isInteger("123")); //=> true
        System.out.println(IntegerUtils.isInteger("١٢٣")); //=> true        
    }
    

    /**
     *Determines if the string is a decimal integer and falls within the int category.
     * @param str The character string to be judged.
     * @True if the return string is a decimal integer and falls within the int category.
     */
    public static final boolean isInteger(String str) {
        if (str == null
        		|| str.isEmpty()
        		|| str.equals("+")
        		|| str.equals("-")) {
            return false;
        }

        char first = str.charAt(0);
        int i = (first == '+' || first == '-') ? 1 : 0;
        int sign = (first == '-') ? -1 : 1;
        int len = str.length();
        long integer = 0;

        while (i < len) {
        	char ch = str.charAt(i++);
            int digit = Character.digit(ch, 10);
            if (digit == -1) {
            	return false;
            }

            integer = integer * 10 + sign * digit;
            if (integer < Integer.MIN_VALUE || Integer.MAX_VALUE < integer) {
                return false;
            }
        }
        return true;
    }



//    ==== 2017-05-16 There was an error in the logic, so it was completely corrected.===
//    /**
//     *Determines if the string is a decimal integer and falls within the int category.
//     * @param str The character string to be judged.
//     * @True if the return string is a decimal integer and falls within the int category.
//     */
//    public static final boolean isInteger(String str) {        
//        if (str == null || str.isEmpty()) {
//            return false;
//        }
//        
//        boolean isNegative = str.charAt(0) == '-';
//        int i = isNegative ? 1 : 0;
//        int sign = isNegative ? -1: 1;
//        int len = str.length();
//        long integer = 0;
//        
//        while (i < len) {
//            int digit = str.charAt(i++) - '0';
//            if (digit < 0 || 9 < digit) {
//                return false;
//            }
//            
//            integer = integer * 10 + sign * digit;
//            if (integer < Integer.MIN_VALUE || Integer.MAX_VALUE < integer) {
//                return false;
//            }
//        }
//        return true;
//    }
}

It's an algorithm, or something very simple, it just checks character by character to see if a given argument can be converted to an integer. The only difference from using ʻInteger # parseInt` is that it doesn't use exceptions, but I personally feel that it's more sophisticated than "false if it's an exception". Self-satisfaction (´ ・ ω ・ `)

Recommended Posts

Check if a string can be converted to an int without using Integer # parseInt
Library to check if it is an IPv4 format string
Find a Switch statement that can be converted to a Switch expression
When you want to check whether the contents of a property can be converted to a specific type
Write a null case using the Optional type without using an if statement
I installed WSL2 without using Microsoft Store and tried to build an environment where Docker can be used
[Java] How to convert one element of a String type array to an Int type
How to check if an instance variable is defined in a Ruby class
[Java] char type can be cast to int type
[Ruby] Get a 3-digit integer and conditionally branch using an if statement (digits method)