电子邮件验证错误

时间:2018-09-26 01:34:53

标签: java

我正在尝试编写代码,以根据给定条件检测电子邮件地址是否有效。我的代码似乎适用于所有条件,但电子邮件中没有'@'时除外。当它没有'@'时,出现字符串超出范围错误。有什么建议吗?

import java.util.Scanner;

公开课电子邮件{ 公共静态void主(String [] args){

//Create Scanner Object

Scanner stdin = new Scanner(System.in);

//prompt user for email address

System.out.print("Enter your email address: ");
String email = stdin.next();
email.length();

//shows location of @ and . characters

int atIndex = email.indexOf('@');
int finalperiodIndex = email.indexOf('.');
int periodIndex = email.indexOf('.');

//shows if email is valid or not

String invalid = "email is not valid";
String valid = "email is valid";
String location = email.substring(atIndex+1, email.length());
String userName = email.substring(0, atIndex);

//if the email does not have an '@' or '.' it is not valid

if((atIndex == -1) ||(periodIndex == -1)) {
    System.out.println(invalid);


//if the first character is a '@' it is not valid

}
else if (atIndex == 0) {
    System.out.println(invalid);

// if the last character is a '.' the email is invalid  

}
else if(periodIndex == email.length()-1) {
    System.out.println(invalid);
}
//if the final '.' is before the '@' the email is invalid

else if(finalperiodIndex < atIndex) {
    System.out.println(invalid);
}
//if there is a '.' before the '@' it's invalid

else if (email.indexOf('.') < email.indexOf('.')) {
    System.out.println(invalid);
}

//if there is no space between the '@' and '.' its invalid

else if (location.length()== -1) {
    System.out.println(invalid);
}
else {
    //end if 

    // print "valid" as well as domain and username

    System.out.println(valid);
    System.out.println("Username is: " + userName);
    System.out.println("Domain is: " + location);

1 个答案:

答案 0 :(得分:0)

在尝试执行子字符串之前,将if((atIndex == -1) ||(periodIndex == -1))检查移到实现的更高位置。另外,如果此条件为真,请确保停止验证逻辑(不知道在哪里实现,但如果是方法,则请确保返回false或引发异常等)。