0 votes
1 view
in Java by (7.9k points)

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

public boolean isInteger( String input ) {

    try {

        Integer.parseInt( input );

        return true;

    }

    catch( Exception e ) {

        return false;

    }

}

Is it just me, or does this seem a bit hackish? What's a better way?

1 Answer

0 votes
by (39.8k points)

If you are not involved with potential overflow difficulties this function will make about 20-30 times more durable than using Integer.parseInt().

public static boolean isInteger(String str) {

    if (str == null) {

        return false;

    }

    int length = str.length();

    if (length == 0) {

        return false;

    }

    int i = 0;

    if (str.charAt(0) == '-') {

        if (length == 1) {

            return false;

        }

        i = 1;

    }

    for (; i < length; i++) {

        char c = str.charAt(i);

        if (c < '0' || c > '9') {

            return false;

        }

    }

    return true;

}

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...