简体   繁体   中英

check password for digits and letters

I have problem with two of my methods for password validation. The method hasDigitsAndLetters is supposed to check whether all the characters of the String are digits and letters and the second method hasTwoDigits is supposed to check whether there are at least two digits in the pass, but the problem is that for expected result true they are ruturning false. If someone can help. here is the code.

//check if the whole string consists of digits and letters
    public static boolean hasDigitsAndLetters(String pass)
    {
        for(int i=0; i<pass.length(); i++)
        {
            if(!Character.isLetterOrDigit((i)))
            {
                return false;
            }

        }
        return true;
    }



    // check whether the password has at least 2 digits
    public static boolean hasTwoDigits(String pass)
    {
        int counter = 0;
        for(int i=0; i<pass.length(); i++)
        {
            if(Character.isDigit(i))
            {
                counter ++;
            }

        }
        System.out.println("Number of digits: " + counter);
        if(counter >= 2)
        {
            return true;
        }
        return false;
    }

You need to pass character at position i for that String.

Character.isLetterOrDigit((pass.charAt(i)))

same for digit also

Character.isDigit((pass.charAt(i)))

您想检查索引i处字符串中的字符,而不是索引变量本身:

Character.isLetterOrDigit(pass.charAt(i))

You aren't checking against characters in your pass , you need to change your checks to:

if(!Character.isLetterOrDigit((pass.charAt(i)))

and

if(Character.isDigit(pass.charAt(i)))

Right now you are checking if i is a digit or letter and i is an int. You need to check the character at position i.

if(Character.isDigit(pass.charAt(i)))

The error is that you're comparing the position into the string rather than the character at that position in the string. I'd probably not use charAt , however... there's no point in keeping explicit management of the position here. I suggest you use String.toCharArray instead.

public static boolean isAlphanumeric(final String str) {
  for (char c : str.toCharArray()) {
    if (!Character.isLetterOrDigit(c)) {
      return false;
    }
  }
  return true;
}

public static boolean isBidigital(final String str) {
  int n = 0;
  for (char c : str.toCharArray()) {
    if (Character.isDigit(c)) {
      ++n;
    }
  }
  return n >= 2;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM