0

I'm trying to run a check whether or not a user has entered the @gmail.com suffix to their input. If not, then append it. I'm having a little difficulty because this loop seems to be written correctly to me. I'm at a loss. Anyone? I'm sure it's simple, I just can't see it.

String UN;
Scanner sc = new Scanner(System.in);
String suf = "@gmail.com";
boolean sufd;
// your code goes here
UN = sc.nextLine(); //
if(UN.length() >= 11){
    sufd = UN.substring(UN.length()-11,UN.length()-1).equals("@gmail.com");
    if(!sufd) {
        UN += suf;
    }
} else if(UN.length() < 11) {
    UN += suf;
}
System.out.print(UN);
Jiri Tousek
  • 12,211
  • 5
  • 29
  • 43
Phil C.
  • 114
  • 1
  • 12
  • 4
    That's mighty complex. Why don't you use [String.endsWidth](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#endsWith%28java.lang.String%29)? – Kenney Dec 12 '15 at 17:42
  • 2
    Call me an idiot, but I didn't know that method existed. Thank you. – Phil C. Dec 12 '15 at 17:43

2 Answers2

2

Using the official java email package is the easiest:

public static boolean isValidEmailAddress(String email) {
   boolean result = true;
   try {
      InternetAddress emailAddr = new InternetAddress(email);
      emailAddr.validate();
   } catch (AddressException ex) {
      result = false;
   }
   return result;
}
Rohan Gala
  • 641
  • 5
  • 18
1
    public boolean isValidEmailAddress(String email) {
           String ePattern = "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$";
           java.util.regex.Pattern p = java.util.regex.Pattern.compile(ePattern);
           java.util.regex.Matcher m = p.matcher(email);
           return m.matches();
    }

Test Cases:

enter image description here

.

Rohan Gala
  • 641
  • 5
  • 18