Suppose we have the following problem. User input some value, how to check that this value is a String is an integer:
1. Check by Exception
1 2 3 4 5 6 7 8 9 10 11 12 |
public static void main(String[] args) { System.out.println("Is int? " + IsIntCheckByException("12")); } private static boolean IsIntCheckByException(String str) { try { Integer.parseInt(str); return true; } catch (NumberFormatException nfe) { return false; } } |
2. Check by regular expression
1 2 3 4 5 6 7 |
public static void main(String[] args) { System.out.println("Is int? " + IsIntCheckByRegex("12")); } private static boolean IsIntCheckByRegex(String str) { return str.matches("^-?\\d+$"); } |
3. Check by regular expression with pattern compile
1 2 3 4 5 6 7 8 9 |
private static final Pattern pattern = Pattern.compile("^-?\\d+$"); public static void main(String[] args) { System.out.println("Is int? " + IsIntCheckByCompiledRegex("12")); } private static boolean IsIntCheckByCompiledRegex(String str) { return pattern.matcher(str).find(); } |
4. Check by chars comparsion
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
public static void main(String[] args) { System.out.println("Is int 4? " + IsIntCheckByCharComparsion("12")); } public static boolean IsIntCheckByCharComparsion(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 <= '/' || c >= ':') { return false; } } return true; } |