Created
June 30, 2012 18:04
-
-
Save yanaga/3024877 to your computer and use it in GitHub Desktop.
Código Java para validação do CNS (Cartão Nacional de Saúde)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public boolean isValid(String s) { | |
if (s.matches("[1-2]\\d{10}00[0-1]\\d") || s.matches("[7-9]\\d{14}")) { | |
return somaPonderada(s) % 11 == 0; | |
} | |
return false; | |
} | |
private int somaPonderada(String s) { | |
char[] cs = s.toCharArray(); | |
int soma = 0; | |
for (int i = 0; i < cs.length; i++) { | |
soma += Character.digit(cs[i], 10) * (15 - i); | |
} | |
return soma; | |
} |
Ei Yanaga, ao invés de validar, como poderia usar para GERAR? Eu trabalho com automação de testes e precisaria de gerar CNSs para o teste, consegue me dar essa força?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Olá Yanaga, tudo bem?
Eu estava pesquisando sobre essa validação de CNS e encontrei seu código (muito bom, por sinal).
Não sei exatamente se é necessário nesse caso, mas talvez precise checar o tamanho da string limpa para ver se é 15?