我正在尝试完成编程任务,我必须创建一个“密码验证程序”,它有1个大写,1个小写,1个数字和1个特殊字符。如果无效,则必须显示“无效”以及显示为false的规则。我遇到的问题不是错误信息,但我总是得到积极的回应,加上所有违反的规则,再加上它读两次。这里没什么帮助?
import java.util.Scanner;
public class PasswordVerifier {
public static void main(String[] args) {
System.out.println("Password Verifier");
System.out.println("Enter a password that meets the following rules: ");
System.out.println("-Must be at least 8 characters long" + '\n' +
"-Must contain at least 1 lower case character" + '\n' +
"-Must contain at least 1 upper case character" + '\n' +
"-Must contain at least 1 numeric digit" + '\n' +
"-Must contain at least 1 special character from the set: !@#$%^&*" + '\n' +
"-Must not contain the word 'and' or the word 'end'");
String password;
String contains1 = "and";
String contains2 = "end";
String special = "!@#$%^&*";
Scanner stdIn = new Scanner(System.in);
boolean digit = false; //Has at least 1 digit
boolean upper = true; //Has at least 1 upper case letter
boolean lower = true; //Has at least 1 lower case letter
boolean hasspecial = true; //Has at least 1 special character
boolean length = true; //Has at least 8 digits
boolean endand = true; //Does not contain end or and
boolean valid = false; //Is the password valid?
System.out.println("Enter password: ");
password = stdIn.nextLine();
int result;
result = password.indexOf(contains1);
if (result == -1) {
System.out.println("");
} else {
System.out.println("Must not contain the word 'and'");
}
int result2;
result2 = password.indexOf(contains2);
if (result2 == -1) {
System.out.println("");
} else {
System.out.println("Must not contain the word 'end'");
}
if (password.length() < 8) {
System.out.println("Must be at least 8 characters long.");
} else {
System.out.print("");
}
for (int i = 0; i < password.length(); i++) {
if (!(Character.isUpperCase(password.charAt(i)))) ;
{
upper = false;
valid = false;
i++;
}
if (!(Character.isLowerCase(password.charAt(i)))) ;
{
lower = false;
valid = false;
i++;
}
if (!(Character.isDigit(password.charAt(i)))) ;
{
digit = false;
valid = false;
i++;
}
if (!(password.matches(special))) ;
{
hasspecial = false;
valid = false;
}
if (upper != true) {
System.out.println("Must contain an upper case letter.");
}
if (lower != true) {
System.out.println("Must contain a lower case letter.");
}
if (digit != true) {
System.out.println("Must contain a numeric digit.");
}
if (hasspecial != true) {
System.out.println("Must contain a special character.");
}
if (valid) {
System.out.println("Valid.");
} else if (valid != true) {
System.out.println("Invalid.");
}
}
}
}
答案 0 :(得分:0)
一件事。你所有的if行都是错误的。
您正在添加';'在if之后。这意味着,如果满足if条件,则不执行任何操作,然后始终执行以下行。
另一件事,当你做
时if (!(password.matches(special))) {
hasspecial = false;
valid = false;
}
您要求密码匹配字符串“!@#$%^&amp;(星号)”,它可能不匹配。所以,既然你假设字符串包含一个特殊字符,那么hasspecial将永远为真。你想写一些像password.matches(“。(asterisk)[!@#$%^&amp; *]。(星号))(可能会转义某些字符)。
最后,您要说的是如果字母不符合条件,请将标记设置为false。因此,如果以下字母符合条件,则标记仍为假。你应该通常假设所有条件都是假的,然后在条件满足后将标记设置为真来解决这类问题。
注意:我写了(星号)而不是*,因为文本突出显示,我不知道如何逃避它:(