check password for digits and letters

2019-07-18 03:52发布

问题:

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;
    }

回答1:

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)))


回答2:

You want to check the character in the string at index i, not the index variable itself:

Character.isLetterOrDigit(pass.charAt(i))


回答3:

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)))


回答4:

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)))


回答5:

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;
}