開始使用免費開始

更完善的電子郵件檢查

大家對你做的電子郵件檢查器很滿意,但現在希望它能涵蓋更多情境。你得知並非所有電子郵件都以 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(".");
  }
}
編輯並執行程式碼