Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public final class Ints {
- private Ints() {}
- public static boolean isInt(String value) {
- return isInt(value, DEFAULT_RADIX);
- }
- public static boolean isInt(String value, int radix) {
- if (canNotBeValid(value, radix)) {
- return false;
- }
- int index = findFirstValidNonSignCharacter(value);
- if (index == FIRST_CHARACTER_IS_INVALID) {
- return false;
- }
- return hasValidIntDigits(value, index, radix);
- }
- private static final int MIN_SUPPORTED_RADIX = 2;
- private static final int MAX_SUPPORTED_RADIX = 36;
- private static boolean isSupportedRadix(int radix) {
- return radix >= MIN_SUPPORTED_RADIX && radix <= MAX_SUPPORTED_RADIX;
- }
- private static final int DEFAULT_RADIX = 10; // decimal
- private static boolean isNullOrEmpty(String value) {
- return value == null || value.isEmpty();
- }
- private static boolean canNotBeValid(String value, int radix) {
- return isNullOrEmpty(value) || !isSupportedRadix(radix);
- }
- private static boolean hasValidIntDigits(String value, int index, int radix) {
- int length = value.length();
- while (index < length) {
- int digit = Character.digit(value.charAt(index++), radix);
- if (digit < 0 || digit > radix) {
- return false;
- }
- }
- return true;
- }
- private static final int FIRST_CHARACTER_IS_INVALID = -1;
- private static int findFirstValidNonSignCharacter(String value) {
- char firstCharacter = value.charAt(0);
- if (firstCharacter < '0') {
- switch (firstCharacter) {
- case '-':
- return 1;
- case '+':
- return value.length() > 1 ? 1 : FIRST_CHARACTER_IS_INVALID;
- default:
- return FIRST_CHARACTER_IS_INVALID;
- }
- }
- return firstCharacter == '0'
- ? findFirstValidDigitOfSpecialInt(value)
- : 0;
- }
- // Special strings are strings that contain a radix sign. Like: 0x0, 0b0, etc
- private static final int MIN_SPECIAL_STRING_LENGTH = 3;
- private static final int SPECIAL_STRING_RADIX_SIGN_INDEX = 1;
- private static final int SPECIAL_STRING_FIRST_DIGIT_INDEX = 2;
- private static int findFirstValidDigitOfSpecialInt(String value) {
- if (value.length() < MIN_SPECIAL_STRING_LENGTH) {
- return FIRST_CHARACTER_IS_INVALID;
- }
- switch (value.charAt(SPECIAL_STRING_RADIX_SIGN_INDEX)) {
- case 'x':
- case 'X':
- case 'b':
- case 'B':
- return SPECIAL_STRING_FIRST_DIGIT_INDEX;
- }
- return FIRST_CHARACTER_IS_INVALID;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement