我正在尝试插入一个计数方法,如果用户输入的密码在3次尝试中不符合所需的条件,系统就会退出。我已经尝试了一个计数函数,每次密码不正确时,都会将1添加到计数中,当count == 3,system.exit。我能听听为什么这对我没用的建议吗?密码条件是,至少10个字符,至少一个大写字母,两个或三个数字,只有一个特殊字符。
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Pattern;
public class Test2 {
public static void main(String[] args) {
int count = 0;
System.out.println("Welcome to Humber College");
System.out.println(" ");
System.out.println(" ");
Scanner in = new Scanner(System.in);
System.out.print("Please enter a given password : ");
String password = in.nextLine();
List<String> errorList = new ArrayList<String>();
while (!isValid(password, errorList)) {
System.out.println("The password entered here is invalid");
count = count++;
if (count == 3)
{
System.exit(count);
}
for (String error : errorList) {
System.out.println(error);
}
System.out.print("Please enter a given password : ");
password = in.nextLine();
}
System.out.println("your password is: " + password);
}
public static boolean isValid(String password, List<String> errorList) {
Pattern specailCharPatten = Pattern.compile("[^a-z0-9 ]", Pattern.CASE_INSENSITIVE);
Pattern UpperCasePatten = Pattern.compile("[A-Z ]");
Pattern digitCasePatten = Pattern.compile("[0-9 ]");
errorList.clear();
boolean flag=true;
if (password.length() < 11) {
errorList.add("Password should not be less than 10 characters");
System.out.println(" ");
flag=false;
}
if (!UpperCasePatten.matcher(password).find()) {
errorList.add("Password must have atleast one uppercase character");
System.out.println(" ");
flag=false;
}
if (!digitCasePatten.matcher(password).find()) {
errorList.add("Password should contain 2 or 3 numbers");
System.out.println(" ");
flag=false;
}
if (!specailCharPatten.matcher(password).find()) {
errorList.add("Password must have 1 speacial character");
flag=false;
}
return flag;
}
}发布于 2022-04-02 19:32:13
这不是增加变量的正确方法。
您可以按照以下方式增加或减少变量:假设您有一个整数计数。
First Way:
第二道
第三路
发布于 2022-04-02 19:22:55
count++是count增量的java,然后这个表达式在增量之前解析为count的值。
所以,当你写:
count = count++;并且,假设计数为5,然后这个代码首先递增count (现在是6),然后表达式解析为'5',然后将它赋值为count的新值。所以,现在,计数仍然是 5。
增量的正确方法就是count++。不是count = count++。如果您坚持使用=,您将编写count = count + 1或count += 1 --它们都是相同的。
发布于 2022-04-02 19:17:12
原因是您的计数器没有更新,而是停留在0,这样if就不会触发。只需在while循环中使用count++;而不是count = count++;,它就会按照您的预期工作。
https://stackoverflow.com/questions/71720478
复制相似问题