始める無料で始める

さらに良いメールチェック

あなたのメールチェッカーは大好評で、さらに多くのニーズに合うよう改良してほしいと依頼されました。メールの末尾が必ずしも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(".");
  }
}
コードを編集して実行