RGAlex

O4. Password Validator

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