简体   繁体   中英

How to format a string to an impose format?

I have an homework that requires input validation. How can I format a string to accept just one format type like: AA-1234?

private void validate() {

    Scanner in = new Scanner(System.in);
    System.out.println("Enter the first name:");
    String firstName = in.next();
    System.out.println("Enter the last name:");
    String lastName = in.next();
    System.out.println("Enter the ZIP code");
    String zipCode = in.next();
    System.out.println("Enter the employee ID ");
    String employeeID = in.next();

    if (firstName.length() < 2 | !firstName.matches("[a-zA-z]+")) {
        System.out.println("'" + firstName + "' is not a valid name.Is too short.");
    }
    if (lastName.length() < 2 | !lastName.matches("[a-zA-z]+")) {
        System.out.println("'" + lastName + "' is not a valid name.Is too short.");
    }
    if (!zipCode.matches("[0-9]+")){
        System.out.println("The ZIP code must be numeric.");
    }
    if (!employeeID.matches("%d%d%c%c%c")){
        System.out.println(employeeID +" is not a valid ID format.");
        System.out.println("The ID format should be AA-1234(LetterLetter-NumberNumberNumberNumber)");
    }


}

So I want that my method to accept just ID values with format AA-1234, and if the format is different to print a message that tells you "Your ID format is not valid"

Use a regular expression . Two of "AZ", a dash and then four digits. Something like,

if (!employeeID.matches("[A-Z]{2}-\\d{4}")){
    System.out.println(employeeID +" is not a valid ID format.");
    System.out.println("The ID format should be AA-1234(LetterLetter-NumberNumberNumberNumber)");
}

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