import java.util.Scanner;
public class Toi {
public static void main(String[] args) {
System.out.print("Entrez votre adresse email: " );
Scanner sc = new Scanner(System.in);
String email = sc.nextLine();
// L'adresse e-mail doit avoir un caractère @ et un seul.
if (Toi.oneAndOnly(email, '@')) {
int idAro = email.indexOf('@');
// L'adresse e-mail doit avoir un caractère . et un seul.
if (Toi.oneAndOnly(email, '.')) {
int idDot = email.indexOf('.');
// Ce caractère (@) doit être précédé d'au moins 3 caractères qui ne sont que des lettres de l'alphabet (pas de chiffre).
if (Toi.isAlphaOnly(email, idAro, -3)) {
// Ce caractère (.) doit être suivi d'au moins 2 caractères qui ne sont que des lettres de l'alphabet (pas de chiffre).
if (Toi.isAlphaOnly(email, idDot, 2)) {
// Ce caractère (.) doit être précédé d'au moins 3 caractères qui ne sont que des lettres de l'alphabet (pas de chiffre).
if (Toi.isAlphaOnly(email, idDot, -3)) {
// Ce caractère (.) doit être placé apres le caractère @
if (idAro < idDot) {
System.out.println(email + " is a valid email address" );
} else {
System.out.println(email + " is NOT a valid email address (@ is after .)" );
}
} else {
System.out.println(email + " is NOT a valid email address (Not 3 letters before .)" );
}
} else {
System.out.println(email + " is NOT a valid email address (Not 2 letters after .)" );
}
} else {
System.out.println(email + " is NOT a valid email address (Not 3 letters before @)" );
}
} else {
System.out.println(email + " is NOT a valid email address (. not found or more than once)" );
}
} else {
System.out.println(email + " is NOT a valid email address (@ not found or more than once)" );
}
}
/**
* Checks if char is present only once.
*
* @param aString
* where to search
* @param aChar
* the char to found once
* @return true if there is only one aChar in aString, false otherwise
*/
private static boolean oneAndOnly(String aString, char aChar) {
if (aString == null) {
return false;
}
int nbFound = 0;
for (int lcI = 0; lcI < aString.length(); lcI++) {
if (aString.charAt(lcI) == aChar) {
nbFound++;
}
}
return nbFound == 1;
}
/**
* Checks if substring is composed of letter only.
*
* @param aString
* where to search
* @param aStart
* where to start the substring
* @param aLength
* the length of the substring (if negativ will make substring backward)
* @return true if substring is composed with letter only, false otherwise
*/
private static boolean isAlphaOnly(String aString, int aStart, int aLength) {
if (aString == null) {
return false;
}
int found = 0;
// Backward
if (aLength < 0) {
aStart += aLength;
aLength *= -1;
} else {
aStart += 1;
}
try {
String strTest = aString.substring(aStart, aStart + aLength);
for (int lcI = 0; lcI < strTest.length(); lcI++) {
if (Character.isLetter(strTest.charAt(lcI))) {
found++;
}
}
} catch (StringIndexOutOfBoundsException lc) {
return false;
}
return found == aLength;
}
}