1081 检查密码 (15分) Java题解 PAT (Basic Level) Practice (中文)- 正则最简方法

1081 检查密码 (15分)



原题链接:传送门

一、题目:

在这里插入图片描述

输入样例 1:
5
123s
zheshi.wodepw
1234.5678
WanMei23333
pass*word.6
输出样例 1:
Your password is tai duan le.
Your password needs shu zi.
Your password needs zi mu.
Your password is wan mei.
Your password is tai luan le.


二、解析:

思路:

  对于每个条件直接直接使用正则匹配。
  正则非常有帮助,推荐学习。

AC代码1:最简
import java.util.Scanner;

/**
 * 1081 检查密码 (15分)
 * 
 * @思路:直接使用正则匹配即可
 * @author: ChangSheng 
 * @date:   2019年12月30日 下午3:42:44
 */
public class Main {
	public static void main(String[] args) {
		Scanner s = new Scanner(System.in);
		int N = s.nextInt();
		s.nextLine();
		while(N-- > 0) {
			String password = s.nextLine(), print = null;
			if (password.length() < 6 && print == null) print= "Your password is tai duan le.";
			// 没有匹配到字母、数字、点
			if (!password.matches("[a-zA-Z0-9.]+") && print == null) print = "Your password is tai luan le.";
			// 没有匹配到任意一个数字
			if (!password.matches(".*[0-9].*") && print == null) print = "Your password needs shu zi.";
			// 没有匹配到任意一个字母
			if (!password.matches(".*[a-zA-Z].*") && print == null) print = "Your password needs zi mu.";
			if (print == null) print = "Your password is wan mei.";
			System.out.println(print);
		}
	}
}
AC代码2:
import java.util.Scanner;

/**
 * 1086 就不告诉你 (15分)
 * 
 * @思路:直接使用正则匹配即可
 * @author: ChangSheng 
 * @date:   2019年12月30日 下午3:42:44
 */
public class Main {
	public static void main(String[] args) {
		Scanner s = new Scanner(System.in);
		int N = s.nextInt();
		s.nextLine();
		while(N-- > 0) {
			String password = s.nextLine();
			if (password.length() < 6) {
				System.out.println("Your password is tai duan le.");
				continue;
			}
			// 没有匹配到字母、数字、点
			if (!password.matches("[a-zA-Z0-9.]+")) {
				System.out.println("Your password is tai luan le.");
				continue;
			}
			// 没有匹配到任意一个数字
			if (!password.matches(".*[0-9].*")) {
				System.out.println("Your password needs shu zi.");
				continue;
			}
			// 没有匹配到任意一个字母
			if (!password.matches(".*[a-zA-Z].*")) {
				System.out.println("Your password needs zi mu.");
				continue;
			}
			System.out.println("Your password is wan mei.");
		}
	}
}
发布了86 篇原创文章 · 获赞 104 · 访问量 6632

猜你喜欢

转载自blog.csdn.net/weixin_44034328/article/details/103789203