Advertisement
Guest User

Untitled

a guest
Oct 22nd, 2019
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.42 KB | None | 0 0
  1. public final class Ints {
  2. private Ints() {}
  3.  
  4. public static boolean isInt(String value) {
  5. return isInt(value, DEFAULT_RADIX);
  6. }
  7.  
  8. public static boolean isInt(String value, int radix) {
  9. if (canNotBeValid(value, radix)) {
  10. return false;
  11. }
  12. int index = findFirstValidNonSignCharacter(value);
  13. if (index == FIRST_CHARACTER_IS_INVALID) {
  14. return false;
  15. }
  16. return hasValidIntDigits(value, index, radix);
  17. }
  18.  
  19. private static final int MIN_SUPPORTED_RADIX = 2;
  20. private static final int MAX_SUPPORTED_RADIX = 36;
  21.  
  22. private static boolean isSupportedRadix(int radix) {
  23. return radix >= MIN_SUPPORTED_RADIX && radix <= MAX_SUPPORTED_RADIX;
  24. }
  25.  
  26. private static final int DEFAULT_RADIX = 10; // decimal
  27.  
  28. private static boolean isNullOrEmpty(String value) {
  29. return value == null || value.isEmpty();
  30. }
  31.  
  32. private static boolean canNotBeValid(String value, int radix) {
  33. return isNullOrEmpty(value) || !isSupportedRadix(radix);
  34. }
  35.  
  36. private static boolean hasValidIntDigits(String value, int index, int radix) {
  37. int length = value.length();
  38. while (index < length) {
  39. int digit = Character.digit(value.charAt(index++), radix);
  40. if (digit < 0 || digit > radix) {
  41. return false;
  42. }
  43. }
  44. return true;
  45. }
  46.  
  47. private static final int FIRST_CHARACTER_IS_INVALID = -1;
  48.  
  49. private static int findFirstValidNonSignCharacter(String value) {
  50. char firstCharacter = value.charAt(0);
  51. if (firstCharacter < '0') {
  52. switch (firstCharacter) {
  53. case '-':
  54. return 1;
  55. case '+':
  56. return value.length() > 1 ? 1 : FIRST_CHARACTER_IS_INVALID;
  57. default:
  58. return FIRST_CHARACTER_IS_INVALID;
  59. }
  60. }
  61. return firstCharacter == '0'
  62. ? findFirstValidDigitOfSpecialInt(value)
  63. : 0;
  64. }
  65.  
  66. // Special strings are strings that contain a radix sign. Like: 0x0, 0b0, etc
  67. private static final int MIN_SPECIAL_STRING_LENGTH = 3;
  68. private static final int SPECIAL_STRING_RADIX_SIGN_INDEX = 1;
  69. private static final int SPECIAL_STRING_FIRST_DIGIT_INDEX = 2;
  70.  
  71. private static int findFirstValidDigitOfSpecialInt(String value) {
  72. if (value.length() < MIN_SPECIAL_STRING_LENGTH) {
  73. return FIRST_CHARACTER_IS_INVALID;
  74. }
  75. switch (value.charAt(SPECIAL_STRING_RADIX_SIGN_INDEX)) {
  76. case 'x':
  77. case 'X':
  78. case 'b':
  79. case 'B':
  80. return SPECIAL_STRING_FIRST_DIGIT_INDEX;
  81. }
  82. return FIRST_CHARACTER_IS_INVALID;
  83. }
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement