Fiz 3 classes … coisa básica para válidação de CPF…
public class Verificador {
private int dig1;
private int dig2;
int Digito1(int resto){
if(resto < 2){
dig1 = 0;
return dig1;
}else{
dig1 = 11 - resto;
return dig1;
}
}
int Digito2(int resto){
if(resto < 2){
dig2 = 0;
return dig2;
}else{
dig2 = 11 - resto;
return dig2;
}
}
int Soma(int tamanhoVetor, char[] cpF, int numeroDecrescendo, boolean b){
int i = 0;
int[] a = new int[tamanhoVetor];
int soma = 0;
if(b == true){
while(i < tamanhoVetor){
for(int x = numeroDecrescendo; x >= 2; x--){
a[i] = Integer.parseInt(String.valueOf(cpF[i]));
soma += a[i] * x;
i++;
}
}
return soma;
}else{
while(i < tamanhoVetor){
for(int x = numeroDecrescendo; x >= 3; x--){
a[i] = Integer.parseInt(String.valueOf(cpF[i]));
soma += a[i] * x;
i++;
}
}
return soma + (dig1 * 2);
}
}
}
public class VerificandoCPF extends Verificador {
private String numeros;
private String ab, digitos;
void setNumeros(String numeros){
this.numeros = numeros;
}
String getNumeros(){
return numeros;
}
void VerificaSeValido(){
char[] cpf = getNumeros().substring(0, 9).toCharArray();
int resto = ((Soma(cpf.length, cpf, 10, true)) % 11);
int dg1 = Digito1(resto);
resto = ((Soma(cpf.length, cpf, 11, false)) % 11);
int dg2 = Digito2(resto);
int a = Integer.parseInt(String.valueOf(getNumeros().charAt(9)));
int b = Integer.parseInt(String.valueOf(getNumeros().charAt(10)));
ab = String.valueOf(a + b);
digitos = String.valueOf(dg1 + dg2);
if(ab.equals(digitos)){
System.out.println("CPF Válido...");
}else{
System.out.println("CPF Inválido...");
}
}
}
public class CpfMain {
public static void main(String[] args) {
VerificandoCPF cpf = new VerificandoCPF();
Scanner sc = new Scanner(System.in);
String numCpf = null;
MeuDisplay();
do{
System.out.print("Entre com o Numero do CPF: ");
numCpf = sc.nextLine();
if(ValidandoEntrada(numCpf) != true){
System.err.println("\"ERRO\" - Entre com 11 Digitos\n");
}
}while(ValidandoEntrada(numCpf) != true);
cpf.setNumeros(numCpf);
cpf.VerificaSeValido();
}
private static void MeuDisplay(){
System.out.println("\n");
System.out.printf("*************************************************\n");
System.out.printf("*** @ Programa para Verificar se CPF e Valido ***\n");
System.out.printf("*************************************************\n");
System.out.printf("*** @ Analise e Desenvolvimento de Sistemas ***\n");
System.out.printf("**************** @ 1 Semestre *******************\n");
System.out.printf("*************************************************\n\n");
}
private static boolean ValidandoEntrada(String numeros){
boolean verifica = false;
verifica = numeros.matches("\\d{11}[1]{11}[2]{11}[3]{11}[4]{11}[5]{11}[6]{11}[7]{11}[8]{11}[9]{11}");
if(verifica == true){
return true;
}else {
return false;
}
}
}
Fiz ele para rodar no console… poderia sim ter adicionado b[/b]Mas foi um teste… Pretendo adicionar mais uma classe para Gerar o Número de CPF… enfim
Aqui funcionou… Avaliem …