0

I am a beginner to Java and currently I have code that looks something like this.

The rules are: no special characters, only lowercase or numbers from 0 to 9.

This code is working fine, but it also takes special characters. Are there any other ways to stop that from happening? No Regex please.

if (Password.length() >= 10 && Password.equals(Password.toLowerCase())) {
    System.out.println("Password: Success");
} else {
    System.out.println("Password: Unsuccessful");
}
ocrdu
  • 2,172
  • 6
  • 15
  • 22

2 Answers2

1

You can use String.codePoints method to get a stream over int values of characters of this string and count quantity of them before first occurrence of non-lowercase and non-digit character. Your code might look something like this:

public static void main(String[] args) {
    System.out.println(isLowerCaseOrDigits("EqwerJ")); // false
    System.out.println(isLowerCaseOrDigits("as56re")); // true
    System.out.println(isLowerCaseOrDigits("vb3451")); // true
    System.out.println(isLowerCaseOrDigits("827136")); // true
    System.out.println(isLowerCaseOrDigits("8271)&")); // false
}
private static boolean isLowerCaseOrDigits(String str) {
    return str.codePoints()
            .takeWhile(ch -> Character.isLowerCase(ch)
                    || Character.isDigit(ch))
            .count() == str.length();
}

Or without stream, you can use String.toCharArray method and iterate over the array of characters of this string. Return false on the first occurrence of non-lowercase and non-digit character:

private static boolean isLowerCaseOrDigits(String str) {
    for (char ch : str.toCharArray()) {
        if (!Character.isLowerCase(ch) && !Character.isDigit(ch)) {
            return false;
        }
    }
    return true;
}
0

You can use IntStream#allMatch method:

private static boolean isLowerCaseOrDigits(String str) {
    return str.codePoints().allMatch(ch ->
            Character.isLowerCase(ch) || Character.isDigit(ch));
}
public static void main(String[] args) {
    Boolean[] arr = {
            isLowerCaseOrDigits("EqwerJ"),
            isLowerCaseOrDigits("as56re"),
            isLowerCaseOrDigits("vb3451"),
            isLowerCaseOrDigits("827136"),
            isLowerCaseOrDigits("8271)&")};

    Arrays.stream(arr).forEach(System.out::println);
    // false
    // true
    // true
    // true
    // false
}

See also: Difference between anyMatch and findAny in java 8