Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- public class PasswordValidator {
- //Password Validator
- //Write a program that checks if a given password is valid. Password rules are:
- // 6 – 10 characters (inclusive);
- // Consists only of letters and digits;
- // Have at least 2 digits.
- //If a password is valid, print "Password is valid". If it is not valid, for every unfulfilled rule print a message:
- // "Password must be between 6 and 10 characters";
- // "Password must consist only of letters and digits";
- // "Password must have at least 2 digits"
- //Examples
- //Input
- //logIn
- // Output:
- // Password must be between 6 and 10 characters
- //Password must have at least 2 digits
- //Input:
- //MyPass123
- // Output:
- // Password is valid
- //Input
- //Pa$s$s
- // Output
- // Output:
- // Password must consist only of letters and digits
- //Password must have at least 2 digits
- //
- //Hints
- //Write a method for each rule.
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- String password = scanner.nextLine();
- boolean pass = false;
- if (checkLength(password) && lettersOrNumbers(password) && checkForTwoDigits(password)) {
- System.out.println("Password is valid");
- } else if (!checkLength(password)) {
- System.out.println("Password must be between 6 and 10 character");
- } else if (!lettersOrNumbers(password)) {
- System.out.println("Password must consist only of letters and digits");
- } else if (!checkForTwoDigits(password)) {
- System.out.println("Password must have at least 2 digits");
- }
- }
- public static boolean checkLength(String password) {
- for (int i = 0; i <= password.length(); i++) {
- if (i >= 5 && i <= 9) {
- return true;
- } else {
- return false;
- }
- }
- return true;
- }
- public static boolean lettersOrNumbers(String password) {
- for (int i = 0; i <= password.length(); i++) {
- char symbol = password.charAt(i);
- if (symbol >= 48 && symbol <= 57) {
- return true;
- } else if (symbol >= 65 && symbol <= 90) {
- return true;
- } else if (symbol >= 97 && symbol <= 122) {
- return true;
- } else {
- return false;
- }
- }
- return true;
- }
- public static boolean checkForTwoDigits(String password) {
- int counter = 0;
- for (int i = 0; i <= password.length(); i++) {
- char symbol = password.charAt(i);
- if (symbol >= 48 && symbol <= 57) {
- counter++;
- }
- }
- if (counter >= 2) {
- return true;
- } else {
- return false;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment