Guest User

Untitled

a guest
Feb 18th, 2018
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.59 KB | None | 0 0
  1. import java.util.stream.IntStream;
  2. import java.util.concurrent.atomic.AtomicInteger;
  3.  
  4. public class CPF {
  5. public static IntStream reverseRangeClosed(int from, int to) {
  6. return IntStream.rangeClosed(from, to).map(i -> to - i + from);
  7. }
  8.  
  9. private static int calcDV(final char[] cpf, final int dv_pos) {
  10. AtomicInteger a = new AtomicInteger();
  11. int dv = reverseRangeClosed(2, dv_pos).map(i -> i * (cpf[a.getAndIncrement()] - 48)).sum() % 11;
  12. return dv < 2 ? 0 : 11 - dv;
  13. }
  14.  
  15. public static String calculateCPFDigits(String cpf) {
  16. if (cpf != null) {
  17. if (!cpf.matches("\\d+")) {
  18. throw new IllegalArgumentException("O CPF informado não contém apenas dígitos");
  19. } else if (cpf.length() >= 1 && cpf.length() < 9) {
  20. return calculateCPFDigits(String.format("%9s", cpf).replace(' ', '0'));
  21. } else if (cpf.length() == 9) {
  22. cpf = cpf + calcDV(cpf.toCharArray(), 10);
  23. return cpf + calcDV(cpf.toCharArray(), 11);
  24. }
  25. throw new IllegalArgumentException("O número de dígitos no CPF informado é superior a 9");
  26. }
  27. throw new IllegalArgumentException("O CPF informado é nulo");
  28. }
  29.  
  30. public static void main (String args[]){
  31. String cpf;
  32.  
  33. if (args.length > 0) {
  34. cpf = args[0];
  35. } else {
  36. System.out.println("Informe os primeiros dígitos do CPF (até 9)");
  37. return;
  38. }
  39.  
  40. try {
  41. System.out.println("CPF completo: " + calculateCPFDigits(cpf));
  42. } catch (IllegalArgumentException e) {
  43. System.out.println(e.getMessage());
  44. }
  45. }
  46. }
Add Comment
Please, Sign In to add comment