Advertisement
desislava_topuzakova

4. Password Validator

Jun 10th, 2022
1,010
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.79 KB | None | 0 0
  1. package Methods;
  2.  
  3. import java.util.Scanner;
  4.  
  5. public class PasswordValidator_04 {
  6. public static void main(String[] args) {
  7. Scanner scanner = new Scanner(System.in);
  8. String password = scanner.nextLine();
  9. //1. дължина
  10. boolean isPasswordLengthValid = isValidLength(password);
  11. if (!isPasswordLengthValid) {
  12. System.out.println("Password must be between 6 and 10 characters");
  13. }
  14.  
  15. //2. съдържание
  16. boolean isPasswordContentValid = isValidContent(password);
  17. if (!isPasswordContentValid) {
  18. System.out.println("Password must consist only of letters and digits");
  19. }
  20.  
  21. //3. брой цифри
  22. boolean isPasswordCountDigitsValid = isValidCountDigits(password);
  23. if (!isPasswordCountDigitsValid) {
  24. System.out.println("Password must have at least 2 digits");
  25. }
  26.  
  27. if (isPasswordLengthValid && isPasswordContentValid && isPasswordCountDigitsValid) {
  28. System.out.println("Password is valid");
  29. }
  30.  
  31. }
  32.  
  33. //метод за валидиране на дължината
  34. //true -> ако дължината е валидна
  35. //false -> ако дължината не е валидна
  36. private static boolean isValidLength (String password) {
  37. //валидна дължина: 6 - 10 вкл
  38. if (password.length() >= 6 && password.length() <= 10) {
  39. return true;
  40. }
  41. //невалидна дължина: Password must be between 6 and 10 characters
  42. else {
  43. return false;
  44. }
  45. //return password.length() >= 6 && password.length() <= 10;
  46. }
  47.  
  48. //метод за валидиране на съдържанието
  49. //true -> ако съдържанието е валидно
  50. //false -> ако съдържанието не е валидно
  51. private static boolean isValidContent (String password) {
  52. for (char symbol : password.toCharArray()) {
  53. if (!Character.isLetterOrDigit(symbol)) {
  54. return false;
  55. }
  56. }
  57. return true;
  58. }
  59.  
  60. //метод, който валидира брой на цифрите
  61. //true -> бр. цифрите >= 2
  62. //false -> бр. цифрите < 2
  63. private static boolean isValidCountDigits (String password) {
  64. int countDigits = 0; //брой на цифрите
  65. for (char symbol : password.toCharArray()) {
  66. if (Character.isDigit(symbol)) {
  67. countDigits++;
  68. }
  69. }
  70. //брой цифрите
  71. /*if (countDigits >= 2) {
  72. return true;
  73. } else {
  74. return false;
  75. }*/
  76.  
  77. return countDigits >= 2;
  78.  
  79. }
  80. }
  81.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement