Advertisement
Ligh7_of_H3av3n

4_PasswordValidator

Feb 2nd, 2024
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.62 KB | None | 0 0
  1. package Uprajneniq;
  2.  
  3. import java.util.Scanner;
  4.  
  5. public class PasswordValidator {
  6.     public static void main(String[] args) {
  7.         Scanner scanner = new Scanner(System.in);
  8.  
  9.         String password = scanner.nextLine();
  10.  
  11.         if (isValidPassword(password)) {
  12.             System.out.println("Password is valid");
  13.         } else {
  14.             if (!isBetween6And10Chars(password)) {
  15.                 System.out.println("Password must be between 6 and 10 characters");
  16.             }
  17.             if (!consistOnlyLettersAndDigits(password)) {
  18.                 System.out.println("Password must consist only of letters and digits");
  19.             }
  20.             if (!hasAtLeast2Digits(password)) {
  21.                 System.out.println("Password must have at least 2 digits");
  22.             }
  23.         }
  24.  
  25.         scanner.close();
  26.     }
  27.  
  28.     public static boolean isValidPassword(String password) {
  29.         return isBetween6And10Chars(password) &&
  30.                 consistOnlyLettersAndDigits(password) &&
  31.                 hasAtLeast2Digits(password);
  32.     }
  33.  
  34.     public static boolean isBetween6And10Chars(String password) {
  35.         int length = password.length();
  36.         return length >= 6 && length <= 10;
  37.     }
  38.  
  39.     public static boolean consistOnlyLettersAndDigits(String password) {
  40.         return password.matches("[a-zA-Z0-9]+");
  41.     }
  42.  
  43.     public static boolean hasAtLeast2Digits(String password) {
  44.         int digitCount = 0;
  45.         for (char c : password.toCharArray()) {
  46.             if (Character.isDigit(c)) {
  47.                 digitCount++;
  48.             }
  49.         }
  50.         return digitCount >= 2;
  51.     }
  52. }
  53.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement