ตรวจสอบอีเมล แบบปรับปรุงแล้ว
ตัวตรวจสอบอีเมลของคุณได้รับเสียงตอบรับที่ดี และมีคำขอให้ปรับปรุงให้รองรับกรณีต่าง ๆ มากขึ้น คุณทราบว่าอีเมลไม่จำเป็นต้องลงท้ายด้วยโดเมน 3 ตัวอักษรเสมอไป จึงต้องนำเรื่องนี้มาปรับใช้ในโค้ด นอกจากนี้ยังได้รับมอบหมายให้เพิ่มข้อความแจ้งเตือนเมื่อไม่มีสัญลักษณ์ @ อยู่ในอีเมลด้วย
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Java ระดับกลาง
คำแนะนำการฝึกหัด
- เพิ่ม logical operator เพื่อตรวจสอบว่ามี
"."อยู่ที่ตำแหน่งใดก็ได้หลัง"@" - ใช้ control flow ที่เหมาะสมเพื่อดักจับอีเมลที่ไม่ถูกต้องทั้งหมด โดยให้ตั้งค่าสถานะอีเมลที่มี
"@"อยู่ในตำแหน่งที่ถูกต้อง หรือ ไม่มี"."อยู่หลัง"@" - ใช้ logical operator ที่เหมาะสมเพื่อให้แสดงข้อความสำหรับอีเมลที่ ไม่ มี
@
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
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(".");
}
}