Advertisement
svephoto

Password Validator [Java]

Jan 10th, 2021
1,902
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.85 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class PasswordValidator {
  4.  
  5.     public static void main(String[] args) {
  6.         Scanner scanner = new Scanner(System.in);
  7.  
  8.         String password = scanner.nextLine();
  9.         boolean isValid = false;
  10.  
  11.         boolean firstRule = passwordLength(password, isValid);
  12.         boolean secondRule = passwordConsistency(password, isValid);
  13.         boolean thirdRule = passwordDigits(password, isValid);
  14.  
  15.         if (firstRule && secondRule && thirdRule) {
  16.             System.out.println("Password is valid");
  17.         }
  18.     }
  19.  
  20.     private static boolean passwordLength(String password, boolean isValid) {
  21.         if (password.length() >= 6 && password.length() <= 10) {
  22.             isValid = true;
  23.         } else {
  24.             System.out.println("Password must be between 6 and 10 characters");
  25.         }
  26.  
  27.         return isValid;
  28.     }
  29.  
  30.     private static boolean passwordConsistency(String password, boolean isValid) {
  31.         for (int i = 0; i < password.length(); i++) {
  32.             if (!Character.isLetter(password.charAt(i)) && !Character.isDigit(password.charAt(i))) {
  33.                 isValid = false;
  34.  
  35.                 System.out.println("Password must consist only of letters and digits");
  36.                 break;
  37.             } else {
  38.                 isValid = true;
  39.             }
  40.         }
  41.  
  42.         return isValid;
  43.     }
  44.  
  45.     private static boolean passwordDigits(String password, boolean isValid) {
  46.         int digitsCounter = 0;
  47.  
  48.         for (int i = 0; i < password.length(); i++) {
  49.             if (Character.isDigit(password.charAt(i))) {
  50.                 digitsCounter++;
  51.             }
  52.         }
  53.  
  54.         if (digitsCounter >= 2) {
  55.             isValid = true;
  56.         } else {
  57.             System.out.println("Password must have at least 2 digits");
  58.         }
  59.  
  60.         return isValid;
  61.     }
  62. }
  63.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement