Guest User

Untitled

a guest
Jul 16th, 2018
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.89 KB | None | 0 0
  1. public class NISSValidator {
  2.  
  3. private NISSValidator() {
  4. }
  5.  
  6. /**
  7. * Validates if a given string niss is valid.
  8. *
  9. * @param niss number to validate
  10. * @return true if the input is valid and false otherwise
  11. */
  12. public static boolean isValid(String niss) {
  13. return hasValidLength(niss) &&
  14. isNumeric(niss) &&
  15. hasValidFirstDigit(niss) &&
  16. hasValidControlDigit(niss);
  17. }
  18.  
  19. private static boolean hasValidLength(String niss) {
  20. return !(niss == null || niss.length() != 11);
  21. }
  22.  
  23. private static boolean isNumeric(String str) {
  24. for (char c : str.toCharArray()) {
  25. if (!Character.isDigit(c)) {
  26. return false;
  27. }
  28. }
  29. return true;
  30. }
  31.  
  32. private static boolean hasValidFirstDigit(String niss) {
  33. return niss.charAt(0) == '1' || niss.charAt(0) == '2';
  34. }
  35.  
  36. /**
  37. * Validates the niss intigrity.
  38. * Sums all the niss digits multiplied by factors array.
  39. * The niss is valid if 9 minus the reminder of the division
  40. * of niss factors by 10 is equal to the niss check digit.
  41. *
  42. * @param niss digits to validate
  43. * @return true if the control digit is valid and false otherwise.
  44. */
  45. private static boolean hasValidControlDigit(String niss) {
  46. int[] nissArray = convertToIntegerArray(niss);
  47. final int[] FACTORS = {29, 23, 19, 17, 13, 11, 7, 5, 3, 2};
  48. int sum = 0;
  49. for (int i = 0; i < FACTORS.length; i++) {
  50. sum += nissArray[i] * FACTORS[i];
  51. }
  52. return nissArray[nissArray.length - 1] == (9 - (sum % 10));
  53. }
  54.  
  55. private static int[] convertToIntegerArray(String niss) {
  56. final int[] ints = new int[niss.length()];
  57. for (int i = 0; i < niss.length(); i++) {
  58. ints[i] = Integer.parseInt(String.valueOf(niss.charAt(i)));
  59. }
  60. return ints;
  61. }
  62. }
Add Comment
Please, Sign In to add comment