某网站要求用户设置的密码必须由不少于8个字符组成,并且只能有英文字母(包括大小写)、数字和@、#、$这3个特殊符号,且必须既有字母、数字和特殊符号当中至少包含2种的组合。
【输入格式】
输入第一行给出一个正整数N(<100),随后N行,每行给出一个用户设置的密码,为不超过80个字符的非空字符串,以回车结束。
【输出格式】
对每个用户的密码,在一行中输出系统反馈信息,分以下4种:如果密码合法,输出“密码合法”;
如果密码太短,不论合法与否,都输出“密码太短了”;
如果密码长度合法,但存在不合法字符,则输出“密码中存在非法字符”;如果密码长度合法,但只有字母、或只有数字、或只有特殊字符,则输出“密码过于简单”。
【输入样例】
886
123456789
password@119
**pwdhello
【输出样例】
密码太短了
密码过于简单
1、判断长度是否小于8
2、判断是否存在非法字符
3、判断是否仅包含数字、字母、特殊字符其中一类
import java.util.Scanner;
import java.util.regex.Pattern;
public class Test {
public static void main(String[] args) {
String regex="[^a-zA-Z0-9@#$]";
String digitRegex="^[0-9]+$";
String letterRegex="^[a-zA-z]+$";
String tRegex="^[@#$]+$";
Scanner in=new Scanner(System.in);
int num=in.nextInt();
for(int i=0;i<num;i++){
in=new Scanner(System.in);
String pass=in.nextLine();
if (pass.length()<8){
System.out.println("密码太短了");
}else if (Pattern.compile(regex).matcher(pass).find()){
System.out.println("密码中存在非法字符");
}else if (Pattern.compile(digitRegex).matcher(pass).find() || Pattern.compile(letterRegex).matcher(pass).find() || Pattern.compile(tRegex).matcher(pass).find()){
System.out.println("密码过于简单");
}else{
System.out.println("密码合法");
}
}
}
}
对应需要导入的包:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Pattern;
public static void main(String[] args) {
List<String> pswList = new ArrayList<>();
Scanner sc = new Scanner(System.in);
System.out.print("请输入一个小于100的正整数:");
int num = sc.nextInt();
for(int i=0; i<num; i++) {
pswList.add(sc.next());
}
String rexOne = "[a-zA-Z]";
String rexTwo = "[0-9]";
String rexThree = "[#@$]";
for(String psw : pswList) {
if(psw.trim().length() < 8) {
System.out.println("密码太短了");
}else {
if(psw.replaceAll(rexOne, "").replaceAll(rexTwo, "").replaceAll(rexThree, "").length() > 0) {
System.out.println("密码密码中存在非法字符");
}else {
int trueNum = 0;
if(Pattern.compile(rexOne).matcher(psw).find()) {
trueNum++;
}
if(Pattern.compile(rexTwo).matcher(psw).find()) {
trueNum++;
}
if(Pattern.compile(rexThree).matcher(psw).find()) {
trueNum++;
}
if(trueNum < 2) {
System.out.println("密码过于简单");
}else {
System.out.println("密码合法");
}
}
}
}
}
运行结果: