gpt4 book ai didi

java - 密码检查、验证和要求

转载 作者:行者123 更新时间:2023-11-30 06:09:56 25 4
gpt4 key购买 nike

我遇到一个问题,需要至少 2 个大写字母、至少 2 个小写字母和 2 个数字。

具体问题如下:

Write an application that prompts the user for a password that contains at least two uppercase letters, at least two lowercase letters, and at least two digits. After a password is entered, display a message indicating whether the user was successful or the reason the user was not successful.

For example, if the user enters "Password" your program should output: Your password was invalid for the following reasons: uppercase letters digits

If a user enters "P4SSw0rd", your program should output: valid password

这是到目前为止我的编码,我遇到了包含输出行的问题。例如,如果某人没有 2 个大写字母并且没有 2 个字母。当写入 1 个字母时,输出中不会包含两次失败。

import java.util.Scanner;
public class ValidatePassword {
public static void main(String[] args) {
String inputPassword;
Scanner input = new Scanner(System.in);
System.out.print("Password: ");
inputPassword = input.next();
System.out.println(PassCheck(inputPassword));
System.out.println("");
}

public static String PassCheck(String Password) {
String result = "Valid Password";
int length = 0;
int numCount = 0;
int capCount = 0;
for (int x = 0; x < Password.length(); x++) {
if ((Password.charAt(x) >= 47 && Password.charAt(x) <= 58) || (Password.charAt(x) >= 64 && Password.charAt(x) <= 91) ||
(Password.charAt(x) >= 97 && Password.charAt(x) <= 122)) {
} else {
result = "Password Contains Invalid Character!";
}
if ((Password.charAt(x) > 47 && Password.charAt(x) < 58)) {
numCount++;
}
if ((Password.charAt(x) > 64 && Password.charAt(x) < 91)) {
capCount++;
}
length = (x + 1);
}
if (numCount < 2) {
result = "Not Enough Numbers in Password!";
}
if (capCount < 2) {
result = "Not Enough Capital Letters in Password!";
}
if (length < 2) {
result = "Password is Too Short!";
}
return (result);
}
}

最佳答案

如果我理解正确的话,你想要做的就是当你输入“密码”时,你没有 2 个大写字母和 2 个数字,所以你的输出应该如下所示:“密码中的数字不足!密码中的大写字母不足!”。我建议两种解决方案:

  1. 如果要将一个字符串添加到另一个字符串,请使用 +,因为您会用另一个结果值覆盖第一个结果值。但这不是最好的解决方案,因为每次向字符串添加值时,都会在字符串池上创建新的字符串。更多信息请点击这里: https://stackoverflow.com/a/1553110/6003541

    result += "Password is Too Short!";

    result = result + "Password is Too Short!";
  2. 我建议使用StringBuilder。使用“append”方法添加结果,最后返回 StringBuilder 对象的 toString() 值。

    StringBuilder sb = new StringBuilder(); 
    if (numCount < 2) {
    sb.append("Not Enough Numbers in Password!");
    sb.append(System.getProperty("line.separator"));
    }
    if (capCount < 2) {
    sb.append("Not Enough Capital Letters in Password!");
    sb.append(System.getProperty("line.separator"));
    }
    if (length < 2) {
    sb.append("Password is Too Short!");
    }

    return sb.toString();

关于java - 密码检查、验证和要求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50480579/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com