Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.stream.IntStream;
- import java.util.concurrent.atomic.AtomicInteger;
- public class CPF {
- public static IntStream reverseRangeClosed(int from, int to) {
- return IntStream.rangeClosed(from, to).map(i -> to - i + from);
- }
- private static int calcDV(final char[] cpf, final int dv_pos) {
- AtomicInteger a = new AtomicInteger();
- int dv = reverseRangeClosed(2, dv_pos).map(i -> i * (cpf[a.getAndIncrement()] - 48)).sum() % 11;
- return dv < 2 ? 0 : 11 - dv;
- }
- public static String calculateCPFDigits(String cpf) {
- if (cpf != null) {
- if (!cpf.matches("\\d+")) {
- throw new IllegalArgumentException("O CPF informado não contém apenas dígitos");
- } else if (cpf.length() >= 1 && cpf.length() < 9) {
- return calculateCPFDigits(String.format("%9s", cpf).replace(' ', '0'));
- } else if (cpf.length() == 9) {
- cpf = cpf + calcDV(cpf.toCharArray(), 10);
- return cpf + calcDV(cpf.toCharArray(), 11);
- }
- throw new IllegalArgumentException("O número de dígitos no CPF informado é superior a 9");
- }
- throw new IllegalArgumentException("O CPF informado é nulo");
- }
- public static void main (String args[]){
- String cpf;
- if (args.length > 0) {
- cpf = args[0];
- } else {
- System.out.println("Informe os primeiros dígitos do CPF (até 9)");
- return;
- }
- try {
- System.out.println("CPF completo: " + calculateCPFDigits(cpf));
- } catch (IllegalArgumentException e) {
- System.out.println(e.getMessage());
- }
- }
- }
Add Comment
Please, Sign In to add comment