天天看点

Java - 验证邮箱地址是否符合要求

问题描述:

解析一个邮箱地址是否合法,如果合法则打印出用户名部分和该邮箱所属的网站域名

如果邮箱地址不合法则显示不合法的原因

提示:邮箱地址不合法的因素:

1)    邮箱地址中不包含@或。

2)    邮箱地址中含有多了@或。

3)    邮箱地址中。出现在@的前面

4)    用户名里有其他字符

实现步骤:

类图如下:

Java - 验证邮箱地址是否符合要求
import java.util.Scanner;

public class MailTest {
  /*
   * 1.地址中不包括@ 或 .
   * 2.地址中包括多个 @ 或 .
   * 3.邮箱地址中 . 出现 在@ 前面
   * 4.用户名中出现其他字符
   */
  public static boolean testMail() {
    Scanner sc = new Scanner(System.in);
    String strMail = sc.nextLine();
    
    if(strMail.indexOf("@") == -1 || strMail.indexOf(".") == -1) {
      System.out.println("1");
      return false;
    }
    
    if(strMail.indexOf("@") != strMail.lastIndexOf("@") || strMail.indexOf(".") != strMail.lastIndexOf(".")){
      System.out.println("2");
      return false;
    }
    
    if(strMail.indexOf("@")>strMail.indexOf(".")) {
      System.out.println("3");
      return false;
    }
    
    for(int i = 0; i<strMail.indexOf("@"); i++) {
      if(!((strMail.charAt(i) > 'A' && strMail.charAt(i) < 'Z') || (strMail.charAt(i) > 'a' && strMail.charAt(i) < 'z'))) {
        System.out.println("4");
        return false;
      }
    }
    
    return true;
  }
}