user1809407
user1809407

Reputation:

Check input for number

I'm new to Java. I created this code in order to check input field for string or number.

try {
    int x = Integer.parseInt(value.toString());
} catch (NumberFormatException nFE) {
    // If this is a string send error message
    throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
            "  " + findValue + " must be number!", null));
}

How I can create the same check for number but using just if(){} without try-catch?

Upvotes: 1

Views: 188

Answers (2)

Rohit Jain
Rohit Jain

Reputation: 213203

You can use a pattern with String#matches method: -

String str = "6";

if (str.matches("[-]?\\d+")) {
    int x = Integer.parseInt(str);
}

"[-]?\\d+" pattern will match any sequence of digits, preceded by an optional - sign.

"\\d+" means match one or more digits.

Upvotes: 2

Dunes
Dunes

Reputation: 40683

If you really don't want to explicitly catch the the exception then you'd be better off making a helper method.

eg.

public class ValidatorUtils {

    public static int parseInt(String value) {
        try {
            return Integer.parseInt(value);
        } catch (NumberFormatException e) {
            throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
            "  " + findValue + " must be number!", null));
        }
    }
}

public static void main(String[] args) {

    int someNumber = ValidatorUtils.parseInt("2");
    int anotherNumber = ValidatorUtils.parseInt("nope");

}

This way you don't even need to bother with an if statement, plus your code doesn't have to parse the integer twice.

Upvotes: 0

Related Questions