Java 密码检查器:无需数组转换验证密码
如果不想使用方法来将密码转换为字符数组,可以直接使用字符串的索引访问来遍历密码中的每个字符进行检查。以下是相应的代码示例:
import java.util.Scanner;
public class PasswordChecker {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String password;
do {
System.out.print("请输入密码:");
password = scanner.nextLine();
if (password.length() < 8) {
System.out.println("密码长度至少为8个字符!");
} else if (!containsLetterAndDigit(password)) {
System.out.println("密码必须同时包含字母和数字!");
}
} while (password.length() < 8 || !containsLetterAndDigit(password));
System.out.println("密码有效!");
}
public static boolean containsLetterAndDigit(String password) {
boolean hasLetter = false;
boolean hasDigit = false;
for (int i = 0; i < password.length(); i++) {
char c = password.charAt(i);
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
hasLetter = true;
} else if (c >= '0' && c <= '9') {
hasDigit = true;
}
if (hasLetter && hasDigit) {
return true;
}
}
return false;
}
}
在这个示例中,我们直接使用字符串的索引访问 password.charAt(i) 来获取密码中的每个字符。然后,我们使用条件语句来检查字符是否是字母或数字,并相应地更新 hasLetter 和 hasDigit 的值。如果在遍历过程中同时找到了字母和数字,我们返回 true 表示密码有效。否则,我们返回 false 表示密码无效。循环会一直进行,直到用户输入一个有效密码为止。
原文地址: https://www.cveoy.top/t/topic/oap 著作权归作者所有。请勿转载和采集!