gpt4 book ai didi

java - 如何将字符串格式化为强加格式?

转载 作者:行者123 更新时间:2023-12-02 01:26:00 25 4
gpt4 key购买 nike

我有一个作业需要输入验证。如何格式化字符串以仅接受一种格式类型,例如: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 格式无效”

最佳答案

使用正则表达式。两个“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)");
}

关于java - 如何将字符串格式化为强加格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56911601/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com