Dido09

Класът Random - Homework

Nov 6th, 2019
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.52 KB | None | 0 0
  1. import java.util.Random;
  2. public class Digits {
  3.  
  4. private static final String CAPITAL_LETTERS =
  5.  
  6. "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  7.  
  8. private static final String SMALL_LETTERS =
  9.  
  10. "abcdefghijklmnopqrstuvwxyz";
  11.  
  12. private static final String DIGITS = "0123456789";
  13.  
  14. private static final String SPECIAL_CHARS =
  15.  
  16. "~!@#$%^&*()_+=`{}[]\\|':;.,/?<>";
  17.  
  18. private static final String ALL_CHARS =
  19.  
  20. CAPITAL_LETTERS + SMALL_LETTERS + DIGITS + SPECIAL_CHARS;
  21.  
  22.  
  23.  
  24. private static Random rnd = new Random();
  25.  
  26.  
  27.  
  28. public static void main(String[] args) {
  29.  
  30. StringBuilder password = new StringBuilder();
  31.  
  32.  
  33.  
  34. // Генерира 2 произволни главни букви
  35.  
  36. for (int i=1; i<=2; i++) {
  37.  
  38. char capitalLetter = generateChar(CAPITAL_LETTERS);
  39.  
  40. insertAtRandomPosition(password, capitalLetter);
  41.  
  42. }
  43.  
  44.  
  45.  
  46. // Генерира 2 произволни малки букви
  47.  
  48. for (int i=1; i<=2; i++) {
  49.  
  50. char smallLetter = generateChar(SMALL_LETTERS);
  51.  
  52. insertAtRandomPosition(password, smallLetter);
  53.  
  54. }
  55.  
  56.  
  57.  
  58. //Генерира се 1 произвона цифра
  59.  
  60. char digit = generateChar(DIGITS);
  61.  
  62. insertAtRandomPosition(password, digit);
  63.  
  64.  
  65.  
  66. // Генерира 3 символа
  67.  
  68. for (int i=1; i<=3; i++) {
  69.  
  70. char specialChar = generateChar(SPECIAL_CHARS);
  71.  
  72. insertAtRandomPosition(password, specialChar);
  73.  
  74. }
  75.  
  76.  
  77.  
  78. // Генерира няколко произвилни символа (между 0 и 7)
  79.  
  80. int count = rnd.nextInt(8);
  81.  
  82. for (int i=1; i<=count; i++) {
  83.  
  84. char specialChar = generateChar(ALL_CHARS);
  85.  
  86. insertAtRandomPosition(password, specialChar);
  87.  
  88. }
  89.  
  90.  
  91.  
  92. System.out.println(password);
  93.  
  94. }
  95.  
  96.  
  97.  
  98. private static void insertAtRandomPosition(
  99.  
  100. StringBuilder password, char character) {
  101.  
  102. int randomPosition = rnd.nextInt(password.length()+1);
  103.  
  104. password.insert(randomPosition, character);
  105.  
  106. }
  107.  
  108.  
  109.  
  110. private static char generateChar(String availableChars) {
  111.  
  112. int randomIndex = rnd.nextInt(availableChars.length());
  113.  
  114. char randomChar = availableChars.charAt(randomIndex);
  115.  
  116. return randomChar;
  117.  
  118. }
  119.  
  120.  
  121.  
  122. }
Add Comment
Please, Sign In to add comment