Write a Java method to check whether a string is a valid password. Each character must be stored in a character array
Password rules:
A password must have at least ten characters.
A password consists of only letters and digits.
A password must contain at least two digits.
Expected Output:
Input a password (You are agreeing to the above Terms and Conditions.): abcd1234
Password is valid: abcd1234
import java.util.Scanner;
public class Main {
public static boolean isValid(char[] password) {
if (password.length < 10) {
return false;
}
int digit = 0;
for (int i = 0; i < password.length; i++) {
if (password[i] > '0' && password[i] < '9') {
digit++;
}
if (!((password[i] > 'a' && password[i] < 'z') ||
(password[i] > 'A' && password[i] < 'Z') ||
(password[i] > '0' && password[i] < '9'))) {
return false;
}
}
return digit >= 2;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Input a password (You are agreeing to the above Terms and Conditions.): ");
String password = in.nextLine();
System.out.println("Password is " + (isValid(password.toCharArray()) ? "valid: " : "invalid: ") + password);
}
}
Comments
Leave a comment