String str1 = sc.nextLine();
另外你这是字符判断,用substring干啥,逐个字符取出来比较就行了啊
遍历一遍字符串:
统计@和.的数量,
记录第一个@和第一个.的位置
然后进行有效条件的判定就可以了
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String email = sc.next();
boolean result = validEmail(email);
}
private static boolean validEmail(String email) {
if(email == null || email.length() == 0){
//email为空
return false;
}
int index1 = email.indexOf("@");
if(index1 == -1){
//@不存在
return false;
}
if(index1 == 0 || index1 == email.length() -1){
//@在第一位,或最后一位
return false;
}
int index2 = email.indexOf("@", index1+1);
if(index2 != -1){
//@多于1个
return false;
}
/*
* 以下字符串中"@"有且仅有一个
*/
int dotIndex1 = email.indexOf(".");
if(dotIndex1 == -1){
//.不存在
return false;
}
if(dotIndex1 == 0 || dotIndex1 == email.length() -1){
//.在第一位,或最后一位
return false;
}
int dotIndex2 = email.indexOf(".", dotIndex1+1);
if(dotIndex2 != -1){
//.多于1个
return false;
}
/*
* 以下字符串中"."有且仅有一个
*/
if(index1 > dotIndex1 ){
//@在.后面
return false;
}
if(dotIndex1 - index1 == 1 ){
//@与.相邻
return false;
}
return true;
}
如果用正则的话是不是代码量很少,,,