The problem
Imagine you are developing a software package for Amazon.com that requires users to enter their own passwords. Your software requires that users' passwords meet the following criteria:
- The password should be at least six characters long.
- The password should contain at least one uppercase and at least one lowercase letter.
- The password should have at least one digit.
Write a class that verifies that a password meets the stated criteria. Demonstrate the class in a program that allows the user to enter a password and then displays a message indicating whether it is valid or not.
Breaking it down
Password class
This exercise will use java 8 predicates extensively. A predicate is often used in mathematics that something that takes a value for an argument and then returns true or false. Each logic check is a java.util.function.Predicate and the isValid
method will chain each predicate together validating the requirements in the problem. The Character:isDigit
, Character:isLowerCase
and Character:isUpperCase
return a predicate so we could of removed the wrapping predicate but if the logic were to change it would require us rewrap.
static class Password {
private String password;
public Password(String password) {
this.password = password;
}
public boolean isValid() {
return hasUpperCase.and(hasLowerCase).and(hasLengthOfSix)
.and(hasAtLeastOneDigit).test(this.password);
}
Predicate<String> hasAtLeastOneDigit = new Predicate<String>() {
@Override
public boolean test(String t) {
return t.chars().anyMatch(Character::isDigit);
}
};
Predicate<String> hasLengthOfSix = new Predicate<String>() {
@Override
public boolean test(String t) {
return t.length() >=6 ? true : false;
}
};
Predicate<String> hasLowerCase = new Predicate<String>() {
@Override
public boolean test(String t) {
return t.chars().anyMatch(Character::isLowerCase);
}
};
Predicate<String> hasUpperCase = new Predicate<String>() {
@Override
public boolean test(String t) {
return t.chars().anyMatch(Character::isUpperCase);
}
};
}
Main
public static void main(String[] args) {
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
// get password to verify logic
System.out.print("Enter a string to represent password: ");
String input = keyboard.nextLine();
// close keyboard
keyboard.close();
// validate
Password password = new Password(input);
boolean validPassword = password.isValid();
System.out.println("The password of " + input + "is "
+ (validPassword ? " valid password " : " an invalid password"));
}
Output
Enter a string to represent password: jwef2323
The password of jwef2323 is an invalid password