Wednesday, December 19, 2012

Determine if a String is an Integer in Java

public static boolean isInteger(String s) {
    try { 
        Integer.parseInt(s); 
    } catch(NumberFormatException e) { 
        return false; 
    }
    // only got here if we didn't return false
    return true;
}
A non exception based method:
public static boolean isInteger(String s) {
    return isInteger(s,10);
}

public static boolean isInteger(String s, int radix) {
    if(s.isEmpty()) return false;
    for(int i = 0; i < s.length; i++) {
        if(i == 0 && s.charAt(i) == '-') continue;
        if(Character.digit(s.charAt(i),radix) < 0) return false;
    }
    return true;
}
http://stackoverflow.com/questions/5439529/determine-if-a-string-is-an-integer-in-java 

No comments:

Post a Comment