密码检查、验证和要求

Password Checking, Verification and Requirements

我有一个问题需要至少 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);
  }
}

如果我理解正确你想要做的是当你输入例如 "Password" 你没有 2 个大写字母和 2 个数字所以你的输出应该是这样的: "Not Enough Numbers in Password! Not Enough Capital Letters in Password!"。 我建议 2 个解决方案:

  1. 如果你想将一个字符串添加到另一个字符串,请使用 + 因为你用另一个覆盖了第一个结果值。但这不是最佳解决方案,因为每次向 String 添加值时,都会在 String 池中创建新的 String。更多信息在这里:

    result += "Password is Too Short!";
    

    result = result + "Password is Too Short!";
    
  2. 我建议使用StringBuilder。使用方法 "append" 添加您的结果,并在末尾 return 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();