更完善的邮箱检查
大家对您之前的邮箱检查器非常满意,但现在希望进一步完善以覆盖更多场景。有人指出,并非所有邮箱地址都以 3 个字符结尾,因此请将这一点纳入代码中。此外,还要求在缺少 @ 符号时给出提示信息。
本练习是课程的一部分
Java 中级
练习说明
- 添加一个逻辑运算,检查在
"@"之后的任意位置是否存在".""。 - 使用合适的控制流来捕获所有不合规的邮箱——需要标记右侧有
"@"或 在"@"之后不包含"."的邮箱。 - 使用正确的逻辑运算符,确保对于不包含
@的邮箱,我们会给出提示信息。
交互式实操练习
通过完成这段示例代码来试试这个练习。
class EMailChecker {
public static void main(String[] args) {
String adrs = "[email protected]";
int addLen = adrs.length();
boolean hasAt = adrs.contains("@");
if (hasAt && adrs.charAt(addLen - 4) == '.') {
System.out.println("Send that email !");
// Enter the correct logical operator to be able to catch all correct emails
} else if (hasAt && (adrs.charAt(addLen - 3) == '.' ____ hasDotAfterAt(adrs))) {
System.out.println("That's a correct email address");
// Use the correct keyword to catch any bad email addresses
} ____ {
// Make sure that the users know when the '@' is missing
if (____hasAt) {
System.out.println("Your email is missing the '@'");
} else {
System.out.println("That's not a valid email");
}
}
}
static boolean hasDotAfterAt(String address) {
int atPos = address.indexOf('@');
String subString = address.substring(atPos);
return subString.contains(".");
}
}