2017-05-09 44 views
1
public static void emailChecker() { 
    Scanner input = new Scanner(System.in); 
    String email = " "; 
    char[] test; 
    int counter = 0; 

    System.out.println("Please enter your email: "); 
    email = input.nextLine(); 

    test = email.toCharArray(); 

    for (int i = 0; i < email.length(); i++) { 
     if (test[i] == 64 || test[i] == 46) { 
      System.out.println("Email is valid"); 
     } else { 
      System.out.println("Email is not valid"); 
     } 
    } 

} 

我发现在第10行输出会说如果字符串包含一个“。”,那么email将是有效的。或“@”。但是我希望我的代码只在“。”时表示该字符串是有效的。在“@”之后。有效的电子邮件示例是:[email protected]如何检查“。”在java中“@”之后?

+0

使用正则表达式,你可以做一个更好的验证器:http://stackoverflow.com/questions/8204680/java-regex-email。看到这个答案。 –

+0

不......这不是一个很好的电子邮件验证方式。相反,看看使用正则表达式。有_many_其他无效的输入,你的例子没有打算涵盖。 –

+0

我只应该使用数组来检查它是否工作。但我没有理解它背后的逻辑。 – Lance

回答

0

试试这个,它会给你输出。

public static void emailChecker() { 
     Scanner input = new Scanner(System.in); 
     String email = " "; 
     char[] test; 
     int counter = 0; 

     System.out.println("Please enter your email: "); 
     email = input.nextLine(); 

     test = email.toCharArray(); 
     boolean valid = false; 

     for (int i = 0; i < email.length(); i++) { 
      if (test[i] == 64){ 
       for(int y=(i+1); y<email.length(); y++){ 
        if(test[y] == 46){ 
         valid = true; 
        } 
       } 
      } 
     } 

     if(valid == true){ 
      System.out.println("Email is valid"); 
     }else{ 
      System.out.println("Email is not valid"); 
     } 
} 
+0

非常感谢,完全有道理。 Idk为什么我没有想到这一点。 – Lance

0

正则表达式是验证电子邮件ID格式最简单的方法。如果你想好工作示例,请参阅

https://www.mkyong.com/regular-expressions/how-to-validate-email-address-with-regular-expression/

如果你还想去与字符数组的比较,这里使用两个附加的int变量有过验证的精细控制的样本代码..

public static void emailChecker() { 
    Scanner input = new Scanner(System.in); 
    String email = " "; 
    char[] test; 
    System.out.println("Please enter your email: "); 
    email = input.nextLine(); 
    test = email.toCharArray(); 

    int fountAtTheRateAt = -1; 
    int fountDotAt = -1; 

    for (int i = 0; i < email.length(); i++) { 
     if (test[i] == 46) { 
      fountDotAt = i; 
     } else if (test[i] == 64) { 
      fountAtTheRateAt = i; 
     } 
    } 
    // at least 1 char in between @ and . 
    if (fountDotAt != fountAtTheRateAt && (fountAtTheRateAt+ 1) < fountDotAt) { 
     System.out.println("Email is valid"); 
    } else { 
     System.out.println("Email is not valid"); 
    } 
    input.close(); 
} 
0

下面是使用循环的问题的一个答案。

但是,正如其他人所评论的,这不是验证电子邮件地址的方法。

boolean foundDot = false; 
boolean foundAt = false; 

for (char c: test) { 
    if (!foundAt) { 
     foundAt = (c == '@'); \\ the () brackets are not required, but makes the code easier to read. 
    } else { 
     foundDot = (c == '.'); 
    } 

    if (foundDot) { 
     valid = true; 
     break; 
    } 
}