-3

我正在编写一个程序来使用以下条件接受用户名和密码 - 用户名必须最少 8 个字符。密码必须至少包含 10 个字符,1 个小写字母,1 个大写字母,密码中应包含 1 个数字。我根据所有条件编写了一个方法 setPassword() 。当我尝试执行时,我收到 StringIndexOutOfBound 异常。我无法理解为什么会出现该错误:

public void setPassword(String password)
{
    char ch;
    if (password.length() <= 10) {
        for (int i = 0; i <= password.length() - 1; i++) {
            ch = password.charAt(i);
            if (Character.isDigit(ch)) {
                for (int j = 0; j <= password.length() - 1; j++) {
                    char ch1 = password.charAt(j);
                    if (Character.isUpperCase(ch1)) {
                        for(int k = 0; k <= password.length(); k++) {
                            char ch2 = password.charAt(k);
                            if (Character.isLowerCase(ch2)) {
                                this.password = password;
                            }
                        }
                    }
                }
            }
        }
    }
}
4

1 回答 1

1

忽略此实现的低效率,以下行:

for(int k = 0; k <= password.length(); k++) {

应该是:

for(int k = 0; k < password.length(); k++) {
//                ^ removed the = from here

或者:

for(int k = 0; k <= password.length() - 1; k++) {
//                                    ^ subtract 1 here

对于以下字符串:

String s = "this-is-a-test";

s.length()会回来的14。该字符串中字符的有效索引是0through 13。使用循环遍历数组的惯用方式for是:

for (int i = 0; i < length_of_array; i++)

您选择改用i <= length_of_array - 1which 实际上是同一件事(尽管更冗长),除了您忽略从长度for中减去的最后一个循环。1

这是根据您提供的标准检查密码有效性的简单方法:

public static boolean isPasswordValid(String password)
{
    if (password.length() < 10) {
        return false;
    }

    int lc = 0, uc = 0, digit = 0;

    for (int i = 0; i < password.length(); i++) {
        char c = password.charAt(i);

        if (Character.isLowerCase(c)) {
            lc++;
        } else if (Character.isUpperCase(c)) {
            uc++;
        } else if (Character.isDigit(c)) {
            digit++;
        }
    }

    return lc > 0 && uc > 0 && digit > 0;
}

true如果所有条件都通过,这将返回,false否则。

于 2018-06-21T18:50:22.610 回答