S.Strachan
S.Strachan

Reputation: 49

parseInt vs isDigit

I need my code to return true if the parameter is the String representation of an integer between 0 and 255 (including 0 and 255), false otherwise.

For example: Strings "0", "1", "2" .... "254", "255" are valid.

Padded Strings (such as "00000000153") are also valid.

isDigit apparently would also work but i was wondering if this would be more beneficial and/or this would even work with Padded Strings?

public static boolean isValidElement(String token) {
    int foo = Integer.parseInt("token");
    if(foo >= 0 && foo <= 255)
        return true;
    else 
        return false;
    }

Upvotes: 2

Views: 475

Answers (4)

acamino
acamino

Reputation: 29

Integer.parseInt throws a NumberFormatException if the conversion is not possible. Having that in mind you can use this code snippet. No additional dependencies are needed.

public static boolean isValidElement(String token) {
    try {
        int value = Integer.parseInt(token);
        return value >= 0 && value <= 255;
    } catch(NumberFormatException e) {
        return false;
    }
}

Upvotes: 0

Abhishek Kedia
Abhishek Kedia

Reputation: 899

isDigit would not work, because it takes a character as input, and returns true if it is a digit from 0 to 9. [Reference : isDigit javadoc]

Since in your case you need to test string representations of all numbers from 0 to 255 hence you must use parseInt.

Additionally also check if the token passed is a valid number by catching NumberFormatException and returning false in case it is not a valid integer.

public static boolean isValidElement(String token) {
    try{
        int foo = Integer.parseInt(token);
        if(foo >= 0 && foo <= 255)
            return true;
        else 
            return false;
    } catch (NumberFormatException ex) {
        return false;
    }
}

Upvotes: 3

AlexC
AlexC

Reputation: 1415

So Integer.parseInt will throw a NumberFormatException if the string is not a valid number, just something to keep in mind.

I would use NumberUtils.isDigit() from commons-math3 library to check, then use Integer.valueOf which is an efficient number parser.

if (NumberUtils.isDigit(token)) {
    int foo = Integer.valueOf(token);
    return (foo >=0 && foo <=255);
}

Upvotes: 0

Bohemian
Bohemian

Reputation: 424993

You could use regex:

return token.matches("1?\\d{1,2}|2[0-4]\\d|25[0-5]");

Upvotes: 0

Related Questions