我有一个作业需要输入验证。 如何格式化字符串以仅接受一种格式类型,例如: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)");
}
}
所以我希望我的方法只接受格式为AA-1234的ID值,如果格式不同,则打印一条消息,告诉您“您的ID格式无效”
答案 0 :(得分:2)
使用正则表达式。 “ A-Z”中的两个,一个破折号,然后是四个数字。像
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)");
}