我的问题是创建一个包含 6 到 10 个字符且至少包含一个字母和一个数字的密码,然后让用户重新输入密码并确认它们匹配。
我遇到的唯一问题是检查密码是否包含字母或数字。我浏览过并在网站上发现了同样的问题,但我对他们在代码中引用的一些方法和其他内容感到困惑,因为我似乎以不同的方式构建了我的。我考虑过使用 indexOf() 方法来查看它是否返回 -1 值,但我不太确定从哪里开始。
我对 java 很陌生,我确信有一种更有效的方法来构建它,我希望得到任何提示。
import java.util.Scanner;
public class Password
{
public static void main(String[] args)
{
//Input from user
String password;
Scanner input = new Scanner(System.in);
System.out.print("Please create your password: ");
password = input.nextLine();
//Checking password length
while( (password.length() < 6) || (password.length() > 10) )
{
System.out.print("This password must be between 6 and 10 characters. Try again: ");
password = input.nextLine();
}
//Checking to see if passwords contain digit/letter
/*Need to add code here */
//Confirming if passwords match
String password2;
System.out.print("\nPlease type your password again to confirm: ");
password2 = input.nextLine();
while( !password2.equals(password) )
{
System.out.print("Those passwords do not match. Try again: ");
password2 = input.nextLine();
}
}
}
最佳答案
使用正则表达式
您应该使用正则表达式来检查这些关键点。
首先,代码:
pwd.matches("^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).{6,10}$")
这是一个完整的示例:
public class HelloWorld{
public static void main(String []args){
String password = "aA2";
String regexp = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).{6,10}$";
System.out.println(password.matches(regexp));
password = "12345678";
System.out.println(password.matches(regexp));
password = "aA345678";
System.out.println(password.matches(regexp));
}
}
给出以下输出:
false
false
true
正则表达式匹配任何字符串,该字符串至少包含大写字母、一个小写字母和一个数字,且长度为 6 - 10 个字符。
您可以找到这些 here 的更多示例。以及有关 Wikipedia 上的正则表达式的一些信息。关于正则表达式和 Java 的非常好的教程可以在 Vogella 上找到。 (我认为这是一个非常好的网站,有非常好的教程!)并且,一个显示正则表达式匹配内容的方便工具:http://www.regexper.com/
在前面的示例中,它为您提供了非常直观的 output 。
没有正则表达式
因此,如果您无法使用正则表达式,我将创建一个函数,如果密码正确,则返回 true,否则返回 false。这是此函数的一个小示例:
public static boolean passwordOk(String password){
if (password == null) return false;
if (password.length() < 6 || password.length() > 10) return false;
boolean containsUpperCase = false;
boolean containsLowerCase = false;
boolean containsDigit = false;
for(char ch: password.toCharArray()){
if(Character.isUpperCase(ch)) containsUpperCase = true;
if(Character.isLowerCase(ch)) containsLowerCase = true;
if(Character.isDigit(ch)) containsDigit = true;
}
return containsUpperCase && containsLowerCase && containsDigit;
}
该解决方案的主要思想是for-each 循环
。我从 String
创建一个字符数组
,并循环遍历其中的元素。如果当前字符是数字、大写字母或小写字母,我会设置一个标志来标记其中一个语句为真。一开始,所有的陈述都是假的,最后我将返回它们相加的结果。
在前两行中,我检查参数是否不为空,以及它的长度是否正确。
我希望,在此之后你能够解决你的作业!即使使用 null
指针,您也可以调用此函数,因此我将创建一个 while
循环,以便在该函数不返回 true
时运行。
如果实在不行,要解决这个问题,here's完整的代码。
相信我,如果您首先尝试自己解决这个问题,它会更有用!
关于Java 密码检查器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26393708/