Pessoal resolvi um exercicio aqui da seguinte forma… funcionou perfeitamente… A duvida é: (Mesmo estando funcional… tem algo que precisa ser mudado?
public class Pessoa {
private String nome;
private int idade;
private String cpf;
public Pessoa(String nome, int idade, String cpf) {
this.nome = nome;
this.idade = idade;
if (cpf.matches("\\d{11}")){
this.cpf = cpf;
}else {
this.setCpf("[telefone removido]");
System.out.println("Cpf invalido");
}
this.formatarCpf();
}
private void formatarCpf(){
String k1 = cpf.substring(0,3);
k1 += “.”;
String k2 = cpf.substring(3,6);
k2 += “.”;
String k3 = cpf.substring(6, 9);
k3 += “-”;
String k4 = cpf.substring(9, 11);
this.cpf = k1+k2+k3+k4;
}