-1

I'm working on a project in school and I need to verify 5 email address from an arraylist.

I have to verify that all emails have '@' and '.' and don't have a space. Right now I'm just trying to get first part down.

This is what I have so far and when it calls it pulls all 5 email addresses. It seems like the contains would check for the chars and only return false on the emails that don't have it. I'm not looking for word for word answer. Just a bit of direction.

public static void print_invalid_emails()
{
    for (Student s : myRoster )
    {
        if(s.getEmailAddress().contains("@.") == false)
            System.out.println("Invalid Email: " + s.getEmailAddress());

    }

}        
Filburt
  • 17,626
  • 12
  • 64
  • 115
Jake
  • 7
  • 1
  • It should be pretty obvious that none of your email address looks like *foo@.com* with a `@.` right next to each other so you will have to split your tests for `@`and `.` – Filburt Mar 21 '17 at 23:57
  • write down your logic on paper first – Scary Wombat Mar 22 '17 at 00:00
  • 1
    And don't try to guess what contains does. Read the javadoc, carefully. https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#contains-java.lang.CharSequence- – JB Nizet Mar 22 '17 at 00:09

1 Answers1

-1

contains check for a String, here your code will return true only if the email adress contains "@." as a String. Try using indexOf :

String email = s.getEmailAddress();

int atIndex = email.indexOf('@');

if (atIndex < 0 || email.indexOf('.', atIndex) < 0 || email.indexOf(' ') >= 0)
    System.out.println("Invalid Email: " + email);

I assumed that the . must be found in the "right part" of the adress, after the @. Otherwise, you don't need atIndex and you can use email.indexOf('.') instead.

You have other ways to check email adress. Check out this post, it may be interesting: What is the best Java email address validation method?

Community
  • 1
  • 1
User9123
  • 396
  • 3
  • 8