I'm trying to make code that detects whether or not an email address is valid based on given conditions. My code seems to work for all the conditions except for when the email does not have an '@'. When it doesn't have an '@' I get a string out of bounds error. Any suggestions?
import java.util.Scanner;
public class email { public static void main (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);