-2

How would I write a program that takes an email address typed in from the keyboard then loops through it looking for an @ sign to see if it has exactly one @ character before printing, "valid," if the email address has one @ sign and "invalid," if the email address has more than one @?

3
  • 2
    See Scanner. And String.indexOf("@")
    – case1352
    Oct 25, 2012 at 21:56
  • 8
    You forgot to ask a question...
    – Sam Dufel
    Oct 25, 2012 at 21:56
  • What program would take an email address typed in from the keyboard then look for an @ to see if it has exactly one @ character in order to check if the email address is valid. Oct 25, 2012 at 22:39

1 Answer 1

11

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;
}

(EDIT) Or simplified:

public static boolean isValidEmailAddress(String email) {
   try {
      new InternetAddress(email).validate();
   } catch (AddressException ex) {
      return false;
   }
   return true;
}
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.