我正在为学校项目制作预订系统。在其中,我需要验证一些字段,并且想知道是否有更好/更有效的方法来实现此目的。
输入示例:
String firstName = "Alex";
String surname = "Smith";
int numberOfGuests = 3;
int numberOfPets = 2;
String email = "[email protected]";
验证:
final int GUEST_MIN = 1;
int guestMax = 4;
final int PETS_MIN = 0;
int petsMax = 4;
boolean presenceCheck = false;
boolean rangeCheck = false;
boolean formatCheck = false;
//Presence Check
if(!(firstName.isEmpty() || surname.isEmpty() || email.isEmpty()))
{
presenceCheck = true;
}
System.out.println(presenceCheck);
//RangeCheck
if(!(numberOfGuests < GUEST_MIN || numberOfGuests > guestMax || numberOfPets < PETS_MIN || numberOfPets > petsMax))
{
rangeCheck = true;
}
System.out.println(rangeCheck);
//Format Check
if(email.contains("@"))
{
formatCheck = true;
}
System.out.println(formatCheck);
我打算对此加以补充,并且想知道是否有一种避免多行if语句的方法。
您的验证也有一些问题。
如果字符串是null
什么?字符串是" "
什么?
对于presenceCheck
,最好编写一个函数:
public static boolean empty(List<String> strings) {
// Null-safe, short-circuit evaluation.
// .trim() removes the whitespace from front and back
// if anyString is null or empty or space, it will return true, else false
return strings.stream().anyMatch(s -> s == null || s.trim().isEmpty());
}
然后您可以这样称呼它:
presenceCheck = empty(Arrays.asList(firstName, lastName, email);
您的rangeCheck没有更好的解决方案。除了删除if这样:
rangeCheck = (!(numberOfGuests < GUEST_MIN || numberOfGuests > guestMax || numberOfPets < PETS_MIN || numberOfPets > petsMax));
仅检查@
电子邮件是不够的,您应该执行以下操作:
public static final Pattern VALID_EMAIL_ADDRESS_REGEX =
Pattern.compile("^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,6}$", Pattern.CASE_INSENSITIVE);
public static boolean validateEmail(String emailStr) {
return VALID_EMAIL_ADDRESS_REGEX.matcher(emailStr).find();
}
formatCheck = validateEmail(email);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句