Static Interface Methods
Completed
Create interface Validator with boolean isValid(String s) and a Java 8 static Validator minLength(int n) factory plus a default Validator and(Validator other). Validate passwords against min length 8 and contains a digit.
Input
n, then n passwords.
Output
n lines: ok or weak.
Example
Input
3 password1 short1 nodigitshere
Output
ok weak weak
Editor
Java
Hints
A lambda can implement any interface with one abstract method.
default methods can combine instances.
Solution explanation
Small composable validators like this are how Java 8 APIs such as Comparator and Predicate are designed.
Show solution
import java.util.Scanner;
interface Validator {
boolean isValid(String s);
static Validator minLength(int n) {
return s -> s.length() >= n;
}
default Validator and(Validator other) {
return s -> isValid(s) && other.isValid(s);
}
}
public class Main {
public static void main(String[] args) {
Validator hasDigit = s -> s.chars().anyMatch(Character::isDigit);
Validator strong = Validator.minLength(8).and(hasDigit);
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
System.out.println(strong.isValid(sc.next()) ? "ok" : "weak");
}
}
}