fork(1) download
  1. import java.util.ArrayList;
  2. import java.text.*;
  3.  
  4. import javax.swing.text.MaskFormatter;
  5.  
  6. class GeraCPF {
  7. private ArrayList<Integer> listaAleatoria = new ArrayList<Integer>();
  8. private ArrayList<Integer> listaNumMultiplicados = null;
  9. public int geraNumAleatorio() {
  10. return (int)(Math.random() * 10);
  11. }
  12. public ArrayList<Integer> geraCPFParcial() {
  13. for (int i = 0; i < 9; i++) listaAleatoria.add(geraNumAleatorio());
  14. return listaAleatoria;
  15. }
  16. public ArrayList<Integer> geraDigito() {
  17. listaNumMultiplicados = new ArrayList<Integer>();
  18. int primeiroDigito;
  19. int totalSomatoria = 0;
  20. int restoDivisao;
  21. int peso = 10;
  22. for (int item : listaAleatoria) listaNumMultiplicados.add(item * peso--);
  23. for (int item : listaNumMultiplicados) totalSomatoria += item;
  24. restoDivisao = (totalSomatoria % 11);
  25. primeiroDigito = restoDivisao < 2 ? 0 : 11 - restoDivisao;
  26. listaAleatoria.add(primeiroDigito);
  27. return listaAleatoria;
  28. }
  29. public String geraCPFFinal() throws ParseException {
  30. //Primeiro executamos os metodos de geracao
  31. geraCPFParcial();
  32. geraDigito();
  33. geraDigito();
  34. String cpf = "";
  35. String texto = "";
  36. for (int item : listaAleatoria) texto += Integer.toString(item);
  37. MaskFormatter mf = new MaskFormatter("###.###.###-##");
  38. mf.setValueContainsLiteralCharacters(false);
  39. cpf = mf.valueToString(texto);
  40. return cpf;
  41. }
  42. public static void main(String[] args) throws ParseException {
  43. System.out.println(new GeraCPF().geraCPFFinal());
  44. }
  45. }
  46.  
  47. //https://pt.stackoverflow.com/q/108289/101
Success #stdin #stdout 0.1s 36200KB
stdin
Standard input is empty
stdout
213.623.887-60