javaregexstring

validate a user input


Hello I'm new to programming and I'm having a trouble understanding my assignment. I know that this might be a really simple problem for you guys and I'm sorry for that. Is it possible that she's just asking me to write a method that will perform the given instructions?

Write a program to find if the user input is valid base on the instructions.**

  1. a string must have at least nine characters
  2. a string consists of letters and numbers only.
  3. a string must contain at least two digits.

Solution

  • Requirement #1: a string must have at least nine characters

    This is solved by checking whether the length of the String is greater than 9, with s.length()>9

    Requirement #2: a string consists of letters and numbers (whole numbers) only.

    Use the regex [a-zA-Z0-9]+, which matches all Latin alphabet characters and numbers.

    Requirement #3: a string must contain at least two digits.

    I've written a method that loops through every character and uses Character.isDigit() to check whether it is a digit.

    Check it out:

    public static boolean verify(String s) {
        final String regex = "[a-zA-Z0-9]+";
        System.out.println(numOfDigits(s));
        return s.length() > 9 && s.matches(regex) && numOfDigits(s) > 2;
    }
    
    public static int numOfDigits(String s) {
        int a = 0;
        int b = s.length();
        for (int i = 0; i < b; i++) {
            a += (Character.isDigit(s.charAt(i)) ? 1 : 0);
        }
        return a;
    }