【发布时间】:2016-07-05 23:00:03
【问题描述】:
所以我写了一个让用户输入密码的方法,这个密码必须通过以下规范:
1. 长度至少为 8 位
2. 大写
3.小写
4.有特殊数字
我不确定为什么当我输入它时,输出没有考虑特殊字符并引发错误。
到目前为止,这是我的代码:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Please enter a given password : ");
String passwordhere = in.nextLine();
System.out.print("Please re-enter the password to confirm : ");
String confirmhere = in.nextLine();
System.out.println("your password is: " + passwordhere);
while (!passwordhere.equals(confirmhere) || !isValid(passwordhere)) {
System.out.println("The password entered here is invalid");
System.out.print("Please enter the password again.it must be valid : ");
String Passwordhere = in.nextLine();
System.out.print("Please re-enter the password to confirm : ");
}
}
public static boolean isValid(String passwordhere) {
if (passwordhere.length() < 8) {
return false;
} else {
for (int p = 0; p < passwordhere.length(); p++) {
if (Character.isUpperCase(passwordhere.charAt(p))) {
}
}
for (int q = 0; q < passwordhere.length(); q++) {
if (Character.isLowerCase(passwordhere.charAt(q))) {
}
}
for (int r = 0; r < passwordhere.length(); r++) {
if (Character.isDigit(passwordhere.charAt(r))) {
}
}
for (int s = 0; s < passwordhere.length(); s++) {
if (Character.isSpecialCharacter(passwordhere.charAt(s))) {
}
}
return true;
}
}
另外,另一个问题是,例如,假设用户输入bob123 作为他们的密码。
我怎样才能让循环告诉用户它需要一个正确的密码?
在上面的示例中,它缺少一个大写字母和一个符号(*&^..etc)。
如何在用户每次输入密码时添加它以打印出来,直到他们获得正确的密码以通过代码的所有规范?
【问题讨论】:
-
@Programminnoob 请对使用正则表达式的密码验证进行一些研究,然后告诉我您发现了什么。 Character.isSpecialCharacter 不是函数,检查特殊字符的最简单方法是使用正则表达式,因此您不妨学习如何正确执行此操作
-
@cricket_007 我怎样才能将其中的任何一个隐含到我的代码中。 ' 返回 (s == null) ? false : s.matches("[^A-Za-z0-9 ]");'也许这条线?
-
替换你不存在的
Character.isSpecialCharacter -
我是否将其用作单独的方法?还是我让它成为一个循环? @cricket_007
标签: java validation passwords