【问题标题】:JAVA: Password criteriaJAVA:密码标准
【发布时间】:2017-03-01 05:11:41
【问题描述】:

提示是:

编写一个 Java 程序,在命令行从用户那里读取一个字符串(密码),然后检查密码是否符合公司密码策略。

政策是:

1) 密码必须至少为 8 个字符

2) 密码必须包含一个大写字母

3) 密码必须包含一位数字。

使用 while 循环单步执行字符串。

如果密码符合则输出“Password OK”,否则输出“Password OK”

输出“密码不符合策略。”

我把它记下来了,但它似乎仍然无法正常工作:

String password = "";
    boolean hasDigitAndUpper = false;
    boolean hasUpper = false;
    int i = 0;

    System.out.print("Please enter a password: ");
    password = scnr.nextLine();

    if (Character.isUppercase(password.charAt(i))){
        if (Character.isUppercase(password.charAt(i))) {
            i++;
            hasDigitAndUpper = true;
        }
    }

    while (password.length() < 8 || hasDigitAndUpper != true) {
        System.out.println("Password does not conform to policy");
        System.out.print("Please enter a password: ");
        password = scnr.nextLine();
    }
    System.out.println("Password OK");

我想我最大的问题是我的布尔值,我不知道如何解决。

【问题讨论】:

  • 弹出的东西:一旦你得到一个新密码,你就不会重新编译hasDigitAndUpper。 Java 不会自动为您更新。
  • 啊。我对编码很陌生,所以我不知道。谢谢你! GhostCat:我整天都在工作和上课,现在才回到这个问题。哈哈。

标签: java passwords


【解决方案1】:

只是一些提示:

if (Character.isUppercase(password.charAt(i))){
    if (Character.isUppercase(password.charAt(i))) {
        i++;
        hasDigitAndUpper = true;
    }
}

再往下你正在使用一个while循环。所以你以前听说过循环。提示:您想要循环整个字符串并检查 all 字符。在我的密码中,大写字符通常会在索引 0 或 1 后面出现。

然后:

while (password.length() < 8 || hasDigitAndUpper != true) {
    System.out.println("Password does not conform to policy");
    System.out.print("Please enter a password: ");
    password = scnr.nextLine();
}

不会做任何合理的事情。您希望该循环围绕其他代码。此代码只是循环并要求用户输入一个包含 8 个字符的新密码 - 其他布尔值 hasDigitAndUpper 具有其 old 值。

所以:你想写一个小方法每个标准;然后你的代码去:

while (not-all-criteria) {
  password = new user input
  check password length
  check password has upper case 
  ...

希望这足以让您继续前进,请理解我不会为您做作业。您迫切需要自己练习这些东西!

【讨论】:

    【解决方案2】:

    您可以使用这个简单的功能。这将遍历密码并检查条件。如果满足所有条件,则返回 true,否则返回 false。

    public static boolean isValid(String pwd)
    {
        if (pwd == null || pwd.length() < 8)
        {
            return false;
        }
        boolean containUpper = false;
        boolean containDigit = false;
        int i = 0;
        while (i < pwd.length())
        {
            if (containDigit && containUpper)
            {
                break;
            }
            if (Character.isUpperCase(pwd.charAt(i)))
            {
                containUpper = true;
            }
            if (Character.isDigit(pwd.charAt(i)))
            {
                containDigit = true;
            }
            i++;
        }
        return containDigit & containUpper;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-18
      • 2011-04-14
      • 1970-01-01
      • 2018-08-16
      • 1970-01-01
      • 2011-08-03
      • 1970-01-01
      相关资源
      最近更新 更多