对于初学者来说,我对Java很陌生,所以我不确定是否有更简单的方法可以做到这一点。我目前正在创建密码检查器。除了我的特殊字符检查外,我的大多数代码都能流畅运行。
我的代码检查长度,是否有数字,但是不检查特殊字符。我目前将if语句设置为如果字符串中的字符之一不是字母,数字或空格,则要设置specialCharCheck = true。否则,请保留为假。
import java.util.Scanner;
public class Project5_Part1 {
public static void main(String[] args) {
String pass;
String confirm;
boolean parameters;
Scanner in = new Scanner(System.in);
System.out.print("Please enter password : ");
pass = in.nextLine();
System.out.print("Please re-enter the password to confirm : ");
confirm = in.nextLine();
parameters = isValid(pass);
while (!pass.equals(confirm) || (!parameters))
{
System.out.println("The password is invalid");
System.out.print("Please enter the password again : ");
pass = in.nextLine();
System.out.print("Please re-enter the password to confirm : ");
confirm = in.nextLine();
parameters = isValid(pass);
}
if (isValid(pass))
{
System.out.println("The password is valid");
}
}
public static boolean isValid(String pass) {
boolean numberCheck = false;
boolean specialCharCheck = false;
if (pass.length() < 8) {
return false;
} else {
for (int i = 0; i < pass.length(); i++)
{
if(Character.isDigit(pass.charAt(i)))
{
numberCheck = true;
}
if (!Character.isLetterOrDigit(i) && !Character.isSpaceChar(i))
{
specialCharCheck = true;
//System.out.println("Test");
}
else
{
specialCharCheck = false;
}
}
return (numberCheck && specialCharCheck);
}
}
}
我错过了一个简单的错误吗?我知道还有另一种方法可以做到这一点,但我觉得这样做更有效。而且逻辑对我来说很有意义。
答案 0 :(得分:1)
Character.isLetterOrDigit(char)需要一个字符作为参数,但是您将其传递为“ int i”。您需要拥有
if (!Character.isLetterOrDigit(pass.charAt(i)) && !Character.isSpaceChar(pass.charAt(i)))
{
specialCharCheck = true;
//System.out.println("Test");
}
else
{
specialCharCheck = false;
}
答案 1 :(得分:-1)
这里有while解决方案:
public static boolean isValid(String pass) {
boolean numberCheck = false;
boolean specialCharCheck = false;
if (pass.length() < 8) {
return false;
} else {
int i = 0;
while (i < pass.length() && (!numberCheck || !specialCharCheck)) {
if (!numberCheck && Character.isDigit(pass.charAt(i))) {
numberCheck = true;
}
if (!specialCharCheck && !Character.isLetterOrDigit(i) && !Character.isSpaceChar(i)) {
specialCharCheck = true;
}
i++;
}
return (numberCheck && specialCharCheck);
}
}