你如何检查"。"来自" @"在java?

时间:2017-05-09 03:59:15

标签: java arrays char

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行输出会说如果字符串包含&#34;那么电子邮件是有效的。&#34;或者&#34; @&#34;。但我希望我的代码只能说&#34;。&#34;时字符串是有效的。来自&#34; @&#34;。有效电子邮件的样本是:email@email.com。

3 个答案:

答案 0 :(得分: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");
        }
}

答案 1 :(得分:0)

RegEx是验证电子邮件ID格式的最简单方法。如果您想要良好的工作示例,请参阅

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

如果您仍想使用char数组比较,这里是一个示例代码,使用两个额外的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();
}

答案 2 :(得分: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;
    }
}